blob: 944f1c0bea239911e0edc0774ab6a36ece368339 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey1a303952011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baidb3c8672012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Robert Greenwalt12e67352014-05-13 21:41:06 -070023import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070024import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070025import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070026import static android.net.ConnectivityManager.isNetworkTypeValid;
27import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070028import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070029
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070030import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070031import android.app.Notification;
32import android.app.NotificationManager;
33import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070034import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.ContentResolver;
36import android.content.Context;
37import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070038import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070040import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090041import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070042import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.net.ConnectivityManager;
44import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070045import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070046import android.net.INetworkPolicyListener;
47import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070048import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080049import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070050import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.MobileDataStateTracker;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070052import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070053import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070054import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070055import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070058import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070059import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070060import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070061import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070063import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070064import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040065import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070066import android.net.RouteInfo;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070067import android.net.SamplingDataTracker;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040068import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040069import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070071import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040072import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070074import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070075import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070076import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Looper;
78import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070079import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070080import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070081import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070082import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070083import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070084import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070086import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040087import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070089import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070090import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070091import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070092import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080093import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070094import android.util.SparseArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070095import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070096import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
Wink Savilleab9321d2013-06-29 21:10:57 -070098import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -040099import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700100import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700101import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700102import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700103import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700104import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700106import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700107import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700108import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700109import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400110import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900111import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700112import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400113import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400114import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700115import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800116import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700117import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700118import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700119import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700120import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700121import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700122
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700123import org.xmlpull.v1.XmlPullParser;
124import org.xmlpull.v1.XmlPullParserException;
125
126import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700128import java.io.FileNotFoundException;
129import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700130import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700132import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700133import java.net.InetAddress;
134import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700135import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700136import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700137import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700138import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700139import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500140import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700141import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700142import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700143import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700144import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146/**
147 * @hide
148 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800149public class ConnectivityService extends IConnectivityManager.Stub
150 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700151 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700153 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700154 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155
Robert Greenwalt31106052014-05-16 17:19:24 -0700156 // network sampling debugging
157 private static final boolean SAMPLE_DBG = false;
158
Jake Hamby786e71a2014-02-06 14:43:50 -0800159 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700160
Jeff Sharkey899223b2012-08-04 15:24:58 -0700161 // TODO: create better separation between radio types and network types
162
Robert Greenwalt42acef32009-08-12 16:08:25 -0700163 // how long to wait before switching back to a radio's default network
164 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
165 // system property that can override the above value
166 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
167 "android.telephony.apn-restore";
168
Wink Savilleab9321d2013-06-29 21:10:57 -0700169 // Default value if FAIL_FAST_TIME_MS is not set
170 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
171 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
172 private static final String FAIL_FAST_TIME_MS =
173 "persist.radio.fail_fast_time_ms";
174
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700175 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
176 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
177
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -0700178 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700179
Jeremy Joslin79294842014-12-03 17:15:28 -0800180 // How long to delay to removal of a pending intent based request.
181 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
182 private final int mReleasePendingIntentDelayMs;
183
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700184 private PendingIntent mSampleIntervalElapsedIntent;
185
186 // Set network sampling interval at 12 minutes, this way, even if the timers get
187 // aggregated, it will fire at around 15 minutes, which should allow us to
188 // aggregate this timer with other timers (specially the socket keep alive timers)
Robert Greenwalt31106052014-05-16 17:19:24 -0700189 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 12 * 60);
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700190
191 // start network sampling a minute after booting ...
Robert Greenwalt31106052014-05-16 17:19:24 -0700192 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 60);
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700193
194 AlarmManager mAlarmManager;
195
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800196 private Tethering mTethering;
197
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700198 private final PermissionMonitor mPermissionMonitor;
199
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700200 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700201
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700202 @GuardedBy("mVpns")
203 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700204
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700205 private boolean mLockdownEnabled;
206 private LockdownVpnTracker mLockdownTracker;
207
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700208 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
209 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700210 /** Currently active network rules by UID. */
211 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700212 /** Set of ifaces that are costly. */
213 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 /**
216 * Sometimes we want to refer to the individual network state
217 * trackers separately, and sometimes we just want to treat them
218 * abstractly.
219 */
220 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 private Context mContext;
223 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700224 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700225 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700227 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800228 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
230 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700231 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700233 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800234 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700235 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700236
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700237 private String mCurrentTcpBufferSizes;
238
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700239 private static final int ENABLED = 1;
240 private static final int DISABLED = 0;
241
Paul Jensenb10e37f2014-11-25 12:33:08 -0500242 // Arguments to rematchNetworkAndRequests()
243 private enum NascentState {
244 // Indicates a network was just validated for the first time. If the network is found to
245 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
246 JUST_VALIDATED,
247 // Indicates a network was not validated for the first time immediately prior to this call.
248 NOT_JUST_VALIDATED
249 };
250 private enum ReapUnvalidatedNetworks {
251 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
252 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
253 // known that there may be unvalidated networks that could potentially be reaped, and when
254 // all networks have been rematched against all NetworkRequests.
255 REAP,
256 // Don't reap unvalidated networks. This should be passed when it's known that there are
257 // no unvalidated networks that could potentially be reaped, and when some networks have
258 // not yet been rematched against all NetworkRequests.
259 DONT_REAP
260 };
261
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700262 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700263 * used internally to change our mobile data enabled flag
264 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700265 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700266
267 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700268 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700269 * from one net to another. Clear happens when we get a new
270 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
271 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700272 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700273 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700274
Robert Greenwalt434203a2010-10-11 16:00:27 -0700275 /**
276 * used internally to reload global proxy settings
277 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700278 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700279
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700280 /**
281 * used internally to set external dependency met/unmet
282 * arg1 = ENABLED (met) or DISABLED (unmet)
283 * arg2 = NetworkType
284 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700285 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700286
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700287 /**
Wink Saville628b0852011-08-04 15:01:58 -0700288 * used internally to send a sticky broadcast delayed.
289 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700290 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700291
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700292 /**
Wink Savilleab9321d2013-06-29 21:10:57 -0700293 * Used internally to disable fail fast of mobile data
294 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700295 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Savilleab9321d2013-06-29 21:10:57 -0700296
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700297 /**
Robert Greenwalt9258c642014-03-26 16:47:06 -0700298 * used internally to indicate that data sampling interval is up
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700299 */
300 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
301
Jason Monkdecd2952013-10-10 14:02:51 -0400302 /**
303 * PAC manager has received new port.
304 */
305 private static final int EVENT_PROXY_HAS_CHANGED = 16;
306
Robert Greenwalte049c232014-04-11 15:53:27 -0700307 /**
308 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700309 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700310 */
311 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
312
Robert Greenwalt7b816022014-04-18 15:25:25 -0700313 /**
314 * used internally when registering NetworkAgents
315 * obj = Messenger
316 */
317 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
318
Robert Greenwalt9258c642014-03-26 16:47:06 -0700319 /**
320 * used to add a network request
321 * includes a NetworkRequestInfo
322 */
323 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
324
325 /**
326 * indicates a timeout period is over - check if we had a network yet or not
327 * and if not, call the timeout calback (but leave the request live until they
328 * cancel it.
329 * includes a NetworkRequestInfo
330 */
331 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
332
333 /**
334 * used to add a network listener - no request
335 * includes a NetworkRequestInfo
336 */
337 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
338
339 /**
340 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400341 * arg1 = UID of caller
342 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700343 */
344 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
345
Robert Greenwalta67be032014-05-16 15:49:14 -0700346 /**
347 * used internally when registering NetworkFactories
348 * obj = Messenger
349 */
350 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
351
Robert Greenwalt27711812014-06-25 16:45:57 -0700352 /**
353 * used internally to expire a wakelock when transitioning
354 * from one net to another. Expire happens when we fail to find
355 * a new network (typically after 1 minute) -
356 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
357 * a replacement network.
358 */
359 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
360
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700361 /**
362 * Used internally to indicate the system is ready.
363 */
364 private static final int EVENT_SYSTEM_READY = 25;
365
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800366 /**
367 * used to add a network request with a pending intent
368 * includes a NetworkRequestInfo
369 */
370 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
371
372 /**
373 * used to remove a pending intent and its associated network request.
374 * arg1 = UID of caller
375 * obj = PendingIntent
376 */
377 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
378
Robert Greenwalta67be032014-05-16 15:49:14 -0700379
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700380 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700381 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700382 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700383 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700384
Mike Lockwood0f79b542009-08-14 14:18:49 -0400385 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800386 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400387
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700388 private PowerManager.WakeLock mNetTransitionWakeLock;
389 private String mNetTransitionWakeLockCausedBy = "";
390 private int mNetTransitionWakeLockSerialNumber;
391 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800392 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700393
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700394 private InetAddress mDefaultDns;
395
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700396 // used in DBG mode to track inet condition reports
397 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
398 private ArrayList mInetLog;
399
Robert Greenwalt434203a2010-10-11 16:00:27 -0700400 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400401 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700402 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700403 private boolean mDefaultProxyDisabled = false;
404
Robert Greenwalt434203a2010-10-11 16:00:27 -0700405 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400406 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700407
Jason Monk602b2322013-07-03 17:04:33 -0400408 private PacManager mPacManager = null;
409
Robert Greenwalt434203a2010-10-11 16:00:27 -0700410 private SettingsObserver mSettingsObserver;
411
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400412 private UserManager mUserManager;
413
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700414 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700415 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700416
Robert Greenwalt50393202011-06-21 17:26:14 -0700417 // the set of network types that can only be enabled by system/sig apps
418 List mProtectedNetworks;
419
John Spurlockbf991a82013-06-24 14:20:23 -0400420 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700421
Wink Savilleab9321d2013-06-29 21:10:57 -0700422 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
423
424 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400425
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700426 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
427 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700428 private final static int MAX_NET_ID = 65535;
429 private int mNextNetId = MIN_NET_ID;
430
Robert Greenwalt34524f02014-05-18 16:22:10 -0700431 // sequence number of NetworkRequests
432 private int mNextNetworkRequestId = 1;
433
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700434 /**
435 * Implements support for the legacy "one network per network type" model.
436 *
437 * We used to have a static array of NetworkStateTrackers, one for each
438 * network type, but that doesn't work any more now that we can have,
439 * for example, more that one wifi network. This class stores all the
440 * NetworkAgentInfo objects that support a given type, but the legacy
441 * API will only see the first one.
442 *
443 * It serves two main purposes:
444 *
445 * 1. Provide information about "the network for a given type" (since this
446 * API only supports one).
447 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
448 * the first network for a given type changes, or if the default network
449 * changes.
450 */
451 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900452
453 private static final boolean DBG = true;
454 private static final boolean VDBG = false;
455 private static final String TAG = "CSLegacyTypeTracker";
456
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700457 /**
458 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
459 * Each list holds references to all NetworkAgentInfos that are used to
460 * satisfy requests for that network type.
461 *
462 * This array is built out at startup such that an unsupported network
463 * doesn't get an ArrayList instance, making this a tristate:
464 * unsupported, supported but not active and active.
465 *
466 * The actual lists are populated when we scan the network types that
467 * are supported on this device.
468 */
469 private ArrayList<NetworkAgentInfo> mTypeLists[];
470
471 public LegacyTypeTracker() {
472 mTypeLists = (ArrayList<NetworkAgentInfo>[])
473 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
474 }
475
476 public void addSupportedType(int type) {
477 if (mTypeLists[type] != null) {
478 throw new IllegalStateException(
479 "legacy list for type " + type + "already initialized");
480 }
481 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
482 }
483
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700484 public boolean isTypeSupported(int type) {
485 return isNetworkTypeValid(type) && mTypeLists[type] != null;
486 }
487
488 public NetworkAgentInfo getNetworkForType(int type) {
489 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
490 return mTypeLists[type].get(0);
491 } else {
492 return null;
493 }
494 }
495
Lorenzo Colittia793a672014-07-31 23:20:17 +0900496 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
497 if (DBG) {
498 log("Sending " + (connected ? "connected" : "disconnected") +
499 " broadcast for type " + type + " " + nai.name() +
500 " isDefaultNetwork=" + isDefaultNetwork(nai));
501 }
502 }
503
504 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700505 public void add(int type, NetworkAgentInfo nai) {
506 if (!isTypeSupported(type)) {
507 return; // Invalid network type.
508 }
509 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
510
511 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
512 if (list.contains(nai)) {
513 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
514 return;
515 }
516
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900517 list.add(nai);
518
519 // Send a broadcast if this is the first network of its type or if it's the default.
520 if (list.size() == 1 || isDefaultNetwork(nai)) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900521 maybeLogBroadcast(nai, true, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700522 sendLegacyNetworkBroadcast(nai, true, type);
523 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700524 }
525
Lorenzo Colittia793a672014-07-31 23:20:17 +0900526 /** Removes the given network from the specified legacy type list. */
527 public void remove(int type, NetworkAgentInfo nai) {
528 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
529 if (list == null || list.isEmpty()) {
530 return;
531 }
532
533 boolean wasFirstNetwork = list.get(0).equals(nai);
534
535 if (!list.remove(nai)) {
536 return;
537 }
538
539 if (wasFirstNetwork || isDefaultNetwork(nai)) {
540 maybeLogBroadcast(nai, false, type);
541 sendLegacyNetworkBroadcast(nai, false, type);
542 }
543
544 if (!list.isEmpty() && wasFirstNetwork) {
545 if (DBG) log("Other network available for type " + type +
546 ", sending connected broadcast");
547 maybeLogBroadcast(list.get(0), false, type);
548 sendLegacyNetworkBroadcast(list.get(0), false, type);
549 }
550 }
551
552 /** Removes the given network from all legacy type lists. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700553 public void remove(NetworkAgentInfo nai) {
554 if (VDBG) log("Removing agent " + nai);
555 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900556 remove(type, nai);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700557 }
558 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700559
Lorenzo Colittia793a672014-07-31 23:20:17 +0900560 private String naiToString(NetworkAgentInfo nai) {
561 String name = (nai != null) ? nai.name() : "null";
562 String state = (nai.networkInfo != null) ?
563 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
564 "???/???";
565 return name + " " + state;
566 }
567
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700568 public void dump(IndentingPrintWriter pw) {
569 for (int type = 0; type < mTypeLists.length; type++) {
570 if (mTypeLists[type] == null) continue;
571 pw.print(type + " ");
572 pw.increaseIndent();
573 if (mTypeLists[type].size() == 0) pw.println("none");
574 for (NetworkAgentInfo nai : mTypeLists[type]) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900575 pw.println(naiToString(nai));
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700576 }
577 pw.decreaseIndent();
578 }
579 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580
581 // This class needs its own log method because it has a different TAG.
582 private void log(String s) {
583 Slog.d(TAG, s);
584 }
585
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700586 }
587 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
588
Jeff Sharkey899223b2012-08-04 15:24:58 -0700589 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700590 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800591 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800592
Robert Greenwalte049c232014-04-11 15:53:27 -0700593 NetworkCapabilities netCap = new NetworkCapabilities();
Robert Greenwalt7569f182014-06-08 16:42:59 -0700594 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
595 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700596 mDefaultRequest = new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -0700597 NetworkRequestInfo nri = new NetworkRequestInfo(null, mDefaultRequest, new Binder(),
598 NetworkRequestInfo.REQUEST);
599 mNetworkRequests.put(mDefaultRequest, nri);
Robert Greenwalte049c232014-04-11 15:53:27 -0700600
Wink Savillebb08caf2010-09-02 19:23:52 -0700601 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
602 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700603 mHandler = new InternalHandler(handlerThread.getLooper());
604 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700605
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800606 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800607 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
608 String id = Settings.Secure.getString(context.getContentResolver(),
609 Settings.Secure.ANDROID_ID);
610 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700611 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800612 SystemProperties.set("net.hostname", name);
613 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800614 }
615
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700616 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700617 String dns = Settings.Global.getString(context.getContentResolver(),
618 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700619 if (dns == null || dns.length() == 0) {
620 dns = context.getResources().getString(
621 com.android.internal.R.string.config_default_dns_server);
622 }
623 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800624 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
625 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800626 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700627 }
628
Jeremy Joslin79294842014-12-03 17:15:28 -0800629 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
630 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
631
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700632 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700633 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800634 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700635 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700636 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700637 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700638
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700639 try {
640 mPolicyManager.registerListener(mPolicyListener);
641 } catch (RemoteException e) {
642 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700643 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700644 }
645
646 final PowerManager powerManager = (PowerManager) context.getSystemService(
647 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700648 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
649 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
650 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800651 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700652
Robert Greenwalt42acef32009-08-12 16:08:25 -0700653 mNetTrackers = new NetworkStateTracker[
654 ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700655
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700656 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700657
Wink Saville51f456f2013-04-23 14:26:51 -0700658 // TODO: What is the "correct" way to do determine if this is a wifi only device?
659 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
660 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700661 String[] naStrings = context.getResources().getStringArray(
662 com.android.internal.R.array.networkAttributes);
663 for (String naString : naStrings) {
664 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700665 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700666 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700667 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800668 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700669 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700670 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700671 }
Wink Saville51f456f2013-04-23 14:26:51 -0700672 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
673 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
674 n.type);
675 continue;
676 }
Wink Saville975c8482011-04-07 14:23:45 -0700677 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800678 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700679 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700680 continue;
681 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700682 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700683
Wink Saville975c8482011-04-07 14:23:45 -0700684 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700685 mNetworksDefined++;
686 } catch(Exception e) {
687 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700688 }
689 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700690
691 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
692 if (mNetConfigs[TYPE_VPN] == null) {
693 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
694 // don't need to add TYPE_VPN to mNetConfigs.
695 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
696 mNetworksDefined++; // used only in the log() statement below.
697 }
698
Wink Saville5e56bc52013-07-29 15:00:57 -0700699 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700700
Robert Greenwalt50393202011-06-21 17:26:14 -0700701 mProtectedNetworks = new ArrayList<Integer>();
702 int[] protectedNetworks = context.getResources().getIntArray(
703 com.android.internal.R.array.config_protectedNetworks);
704 for (int p : protectedNetworks) {
705 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
706 mProtectedNetworks.add(p);
707 } else {
708 if (DBG) loge("Ignoring protectedNetwork " + p);
709 }
710 }
711
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700712 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
713 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700714
Robert Greenwaltfab501672014-07-23 11:44:01 -0700715 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800716
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700717 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
718
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700719 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700720 IntentFilter intentFilter = new IntentFilter();
721 intentFilter.addAction(Intent.ACTION_USER_STARTING);
722 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
723 mContext.registerReceiverAsUser(
724 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900725
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700726 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700727 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700728 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700729 } catch (RemoteException e) {
730 loge("Error registering observer :" + e);
731 }
732
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700733 if (DBG) {
734 mInetLog = new ArrayList();
735 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700736
737 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
738 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800739
John Spurlockbf991a82013-06-24 14:20:23 -0400740 mDataConnectionStats = new DataConnectionStats(mContext);
741 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400742
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700743 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700744
745 IntentFilter filter = new IntentFilter();
746 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
747 mContext.registerReceiver(
748 new BroadcastReceiver() {
749 @Override
750 public void onReceive(Context context, Intent intent) {
751 String action = intent.getAction();
752 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
753 mHandler.sendMessage(mHandler.obtainMessage
754 (EVENT_SAMPLE_INTERVAL_ELAPSED));
755 }
756 }
757 },
758 new IntentFilter(filter));
759
Jason Monkdecd2952013-10-10 14:02:51 -0400760 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700761
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400762 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700764
Robert Greenwalt34524f02014-05-18 16:22:10 -0700765 private synchronized int nextNetworkRequestId() {
766 return mNextNetworkRequestId++;
767 }
768
Paul Jensen60061a62014-08-05 14:13:48 -0400769 private void assignNextNetId(NetworkAgentInfo nai) {
770 synchronized (mNetworkForNetId) {
771 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
772 int netId = mNextNetId;
773 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
774 // Make sure NetID unused. http://b/16815182
775 if (mNetworkForNetId.get(netId) == null) {
776 nai.network = new Network(netId);
777 mNetworkForNetId.put(netId, nai);
778 return;
779 }
780 }
781 }
782 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700783 }
784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 private boolean teardown(NetworkStateTracker netTracker) {
786 if (netTracker.teardown()) {
787 netTracker.setTeardownRequested(true);
788 return true;
789 } else {
790 return false;
791 }
792 }
793
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800794 private NetworkState getFilteredNetworkState(int networkType, int uid) {
795 NetworkInfo info = null;
796 LinkProperties lp = null;
797 NetworkCapabilities nc = null;
798 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800799 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800800
801 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
802 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
803 if (nai != null) {
804 synchronized (nai) {
805 info = new NetworkInfo(nai.networkInfo);
806 lp = new LinkProperties(nai.linkProperties);
807 nc = new NetworkCapabilities(nai.networkCapabilities);
808 network = new Network(nai.network);
Jeff Sharkey32566012014-12-02 18:30:14 -0800809 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800810 }
811 info.setType(networkType);
812 } else {
813 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
814 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
815 info.setIsAvailable(true);
816 lp = new LinkProperties();
817 nc = new NetworkCapabilities();
818 network = null;
819 }
820 info = getFilteredNetworkInfo(info, lp, uid);
821 }
822
Jeff Sharkey32566012014-12-02 18:30:14 -0800823 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400824 }
825
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800826 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
827 if (network == null) {
828 return null;
829 }
830 synchronized (mNetworkForNetId) {
831 return mNetworkForNetId.get(network.netId);
832 }
833 };
834
835 private NetworkState getUnfilteredActiveNetworkState(int uid) {
836 NetworkInfo info = null;
837 LinkProperties lp = null;
838 NetworkCapabilities nc = null;
839 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800840 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800841
842 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800843
844 if (!mLockdownEnabled) {
845 int user = UserHandle.getUserId(uid);
846 synchronized (mVpns) {
847 Vpn vpn = mVpns.get(user);
848 if (vpn != null && vpn.appliesToUid(uid)) {
849 // getUnderlyingNetworks() returns:
850 // null => the VPN didn't specify anything, so we use the default.
851 // empty array => the VPN explicitly said "no default network".
852 // non-empty array => the VPN specified one or more default networks; we use the
853 // first one.
854 Network[] networks = vpn.getUnderlyingNetworks();
855 if (networks != null) {
856 if (networks.length > 0) {
857 nai = getNetworkAgentInfoForNetwork(networks[0]);
858 } else {
859 nai = null;
860 }
861 }
862 }
863 }
864 }
865
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800866 if (nai != null) {
867 synchronized (nai) {
868 info = new NetworkInfo(nai.networkInfo);
869 lp = new LinkProperties(nai.linkProperties);
870 nc = new NetworkCapabilities(nai.networkCapabilities);
871 network = new Network(nai.network);
Jeff Sharkey32566012014-12-02 18:30:14 -0800872 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800873 }
874 }
875
Jeff Sharkey32566012014-12-02 18:30:14 -0800876 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400877 }
878
879 /**
880 * Check if UID should be blocked from using the network with the given LinkProperties.
881 */
882 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700883 final boolean networkCostly;
884 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700885
Robert Greenwalt12e67352014-05-13 21:41:06 -0700886 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700887 synchronized (mRulesLock) {
888 networkCostly = mMeteredIfaces.contains(iface);
889 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700890 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700891
892 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
893 return true;
894 }
895
896 // no restrictive rules; network is visible
897 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700898 }
899
900 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700901 * Return a filtered {@link NetworkInfo}, potentially marked
902 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800903 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700904 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800905 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
906 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400907 // network is blocked; clone and override state
908 info = new NetworkInfo(info);
909 info.setDetailedState(DetailedState.BLOCKED, null, null);
Erik Kline338317e2015-01-19 16:19:09 +0900910 if (DBG) {
911 log("returning Blocked NetworkInfo for ifname=" +
912 lp.getInterfaceName() + ", uid=" + uid);
913 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700914 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800915 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700916 info = mLockdownTracker.augmentNetworkInfo(info);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700917 if (DBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700918 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700919 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700920 }
921
922 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 * Return NetworkInfo for the active (i.e., connected) network interface.
924 * It is assumed that at most one network is active at a time. If more
925 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700926 * @return the info for the active network, or {@code null} if none is
927 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700929 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700931 enforceAccessPermission();
932 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800933 NetworkState state = getUnfilteredActiveNetworkState(uid);
934 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
936
Wink Saville948282b2013-08-29 08:55:16 -0700937 /**
938 * Find the first Provisioning network.
939 *
940 * @return NetworkInfo or null if none.
941 */
942 private NetworkInfo getProvisioningNetworkInfo() {
943 enforceAccessPermission();
944
945 // Find the first Provisioning Network
946 NetworkInfo provNi = null;
947 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700948 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700949 provNi = ni;
950 break;
951 }
952 }
953 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
954 return provNi;
955 }
956
957 /**
958 * Find the first Provisioning network or the ActiveDefaultNetwork
959 * if there is no Provisioning network
960 *
961 * @return NetworkInfo or null if none.
962 */
963 @Override
964 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
965 enforceAccessPermission();
966
967 NetworkInfo provNi = getProvisioningNetworkInfo();
968 if (provNi == null) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800969 provNi = getActiveNetworkInfo();
Wink Saville948282b2013-08-29 08:55:16 -0700970 }
971 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
972 return provNi;
973 }
974
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700975 public NetworkInfo getActiveNetworkInfoUnfiltered() {
976 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800977 final int uid = Binder.getCallingUid();
978 NetworkState state = getUnfilteredActiveNetworkState(uid);
979 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700980 }
981
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700982 @Override
983 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
984 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800985 NetworkState state = getUnfilteredActiveNetworkState(uid);
986 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700987 }
988
989 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 public NetworkInfo getNetworkInfo(int networkType) {
991 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700992 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800993 NetworkState state = getFilteredNetworkState(networkType, uid);
994 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 }
996
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800997 @Override
998 public NetworkInfo getNetworkInfoForNetwork(Network network) {
999 enforceAccessPermission();
1000 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001001 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001002 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1003 if (nai != null) {
1004 synchronized (nai) {
1005 info = new NetworkInfo(nai.networkInfo);
1006 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001007 }
1008 }
1009 return info;
1010 }
1011
1012 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 public NetworkInfo[] getAllNetworkInfo() {
1014 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001015 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001016 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1017 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001018 NetworkInfo info = getNetworkInfo(networkType);
1019 if (info != null) {
1020 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001023 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001026 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001027 public Network getNetworkForType(int networkType) {
1028 enforceAccessPermission();
1029 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001030 NetworkState state = getFilteredNetworkState(networkType, uid);
1031 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1032 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001033 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001034 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001035 }
1036
1037 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001038 public Network[] getAllNetworks() {
1039 enforceAccessPermission();
1040 final ArrayList<Network> result = new ArrayList();
1041 synchronized (mNetworkForNetId) {
1042 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1043 result.add(new Network(mNetworkForNetId.valueAt(i).network));
1044 }
1045 }
1046 return result.toArray(new Network[result.size()]);
1047 }
1048
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001049 private NetworkCapabilities getNetworkCapabilitiesAndValidation(NetworkAgentInfo nai) {
1050 if (nai != null) {
1051 synchronized (nai) {
1052 if (nai.created) {
1053 NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001054 if (nai.lastValidated) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001055 nc.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1056 } else {
1057 nc.removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1058 }
1059 return nc;
1060 }
1061 }
1062 }
1063 return null;
1064 }
1065
1066 @Override
1067 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1068 // The basic principle is: if an app's traffic could possibly go over a
1069 // network, without the app doing anything multinetwork-specific,
1070 // (hence, by "default"), then include that network's capabilities in
1071 // the array.
1072 //
1073 // In the normal case, app traffic only goes over the system's default
1074 // network connection, so that's the only network returned.
1075 //
1076 // With a VPN in force, some app traffic may go into the VPN, and thus
1077 // over whatever underlying networks the VPN specifies, while other app
1078 // traffic may go over the system default network (e.g.: a split-tunnel
1079 // VPN, or an app disallowed by the VPN), so the set of networks
1080 // returned includes the VPN's underlying networks and the system
1081 // default.
1082 enforceAccessPermission();
1083
1084 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1085
1086 NetworkAgentInfo nai = getDefaultNetwork();
1087 NetworkCapabilities nc = getNetworkCapabilitiesAndValidation(getDefaultNetwork());
1088 if (nc != null) {
1089 result.put(nai.network, nc);
1090 }
1091
1092 if (!mLockdownEnabled) {
1093 synchronized (mVpns) {
1094 Vpn vpn = mVpns.get(userId);
1095 if (vpn != null) {
1096 Network[] networks = vpn.getUnderlyingNetworks();
1097 if (networks != null) {
1098 for (Network network : networks) {
1099 nai = getNetworkAgentInfoForNetwork(network);
1100 nc = getNetworkCapabilitiesAndValidation(nai);
1101 if (nc != null) {
1102 result.put(nai.network, nc);
1103 }
1104 }
1105 }
1106 }
1107 }
1108 }
1109
1110 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1111 out = result.values().toArray(out);
1112 return out;
1113 }
1114
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001115 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001116 public boolean isNetworkSupported(int networkType) {
1117 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001118 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001119 }
1120
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001121 /**
1122 * Return LinkProperties for the active (i.e., connected) default
1123 * network interface. It is assumed that at most one default network
1124 * is active at a time. If more than one is active, it is indeterminate
1125 * which will be returned.
1126 * @return the ip properties for the active network, or {@code null} if
1127 * none is active
1128 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001129 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001130 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001131 enforceAccessPermission();
1132 final int uid = Binder.getCallingUid();
1133 NetworkState state = getUnfilteredActiveNetworkState(uid);
1134 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001135 }
1136
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001137 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001138 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001139 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001140 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1141 if (nai != null) {
1142 synchronized (nai) {
1143 return new LinkProperties(nai.linkProperties);
1144 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001145 }
1146 return null;
1147 }
1148
Robert Greenwalt12e67352014-05-13 21:41:06 -07001149 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001150 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001151 public LinkProperties getLinkProperties(Network network) {
1152 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001153 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001154 if (nai != null) {
1155 synchronized (nai) {
1156 return new LinkProperties(nai.linkProperties);
1157 }
1158 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001159 return null;
1160 }
1161
1162 @Override
1163 public NetworkCapabilities getNetworkCapabilities(Network network) {
1164 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001165 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001166 if (nai != null) {
1167 synchronized (nai) {
1168 return new NetworkCapabilities(nai.networkCapabilities);
1169 }
1170 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001171 return null;
1172 }
1173
1174 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001175 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001176 // Require internal since we're handing out IMSI details
1177 enforceConnectivityInternalPermission();
1178
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001179 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001180 for (Network network : getAllNetworks()) {
1181 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1182 if (nai != null) {
1183 synchronized (nai) {
1184 final String subscriberId = (nai.networkMisc != null)
1185 ? nai.networkMisc.subscriberId : null;
1186 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1187 nai.networkCapabilities, network, subscriberId, null));
1188 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001189 }
1190 }
1191 return result.toArray(new NetworkState[result.size()]);
1192 }
1193
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001194 @Override
1195 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1196 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001197 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001198 final long token = Binder.clearCallingIdentity();
1199 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001200 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1201 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001202 try {
1203 return mPolicyManager.getNetworkQuotaInfo(state);
1204 } catch (RemoteException e) {
1205 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001206 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001207 return null;
1208 } finally {
1209 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001210 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001211 }
1212
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001213 @Override
1214 public boolean isActiveNetworkMetered() {
1215 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001216 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001217 final long token = Binder.clearCallingIdentity();
1218 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001219 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001220 } finally {
1221 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001222 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001223 }
1224
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001225 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1226 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1227 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001228 try {
1229 return mPolicyManager.isNetworkMetered(state);
1230 } catch (RemoteException e) {
1231 }
1232 }
1233 return false;
1234 }
1235
Jeff Sharkey216c1812012-08-05 14:29:23 -07001236 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1237 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001238 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001239 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001240 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001241 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001242 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001243
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001244 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 * Ensure that a network route exists to deliver traffic to the specified
1246 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001247 * @param networkType the type of the network over which traffic to the
1248 * specified host is to be routed
1249 * @param hostAddress the IP address of the host to which the route is
1250 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 * @return {@code true} on success, {@code false} on failure
1252 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001253 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001255 if (mProtectedNetworks.contains(networkType)) {
1256 enforceConnectivityInternalPermission();
1257 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001258
Chad Brubakerc0234532014-02-14 13:24:29 -08001259 InetAddress addr;
1260 try {
1261 addr = InetAddress.getByAddress(hostAddress);
1262 } catch (UnknownHostException e) {
1263 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1264 return false;
1265 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001268 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 return false;
1270 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001271
1272 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1273 if (nai == null) {
1274 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1275 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1276 } else {
1277 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1278 }
1279 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001280 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001281
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001282 DetailedState netState;
1283 synchronized (nai) {
1284 netState = nai.networkInfo.getDetailedState();
1285 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001286
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001287 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001288 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001289 log("requestRouteToHostAddress on down network "
1290 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001291 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001292 }
1293 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001295
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001296 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001297 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001298 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001299 LinkProperties lp;
1300 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001301 synchronized (nai) {
1302 lp = nai.linkProperties;
1303 netId = nai.network.netId;
1304 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001305 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001306 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1307 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001308 } finally {
1309 Binder.restoreCallingIdentity(token);
1310 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001311 }
1312
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001313 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001314 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001315 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001316 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001317 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001318 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001319 if (bestRoute.getGateway().equals(addr)) {
1320 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001321 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001322 } else {
1323 // if we will connect to this through another route, add a direct route
1324 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001325 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001326 }
1327 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001328 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001329 try {
1330 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1331 } catch (Exception e) {
1332 // never crash - catch them all
1333 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001334 return false;
1335 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001336 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 }
1338
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001339 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001340 enforceConnectivityInternalPermission();
1341
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001342 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1343 (met ? ENABLED : DISABLED), networkType));
1344 }
1345
1346 private void handleSetDependencyMet(int networkType, boolean met) {
1347 if (mNetTrackers[networkType] != null) {
1348 if (DBG) {
1349 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1350 }
1351 mNetTrackers[networkType].setDependencyMet(met);
1352 }
1353 }
1354
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001355 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1356 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001357 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001358 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001359 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001360 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001361 }
1362
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001363 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001364 // skip update when we've already applied rules
1365 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1366 if (oldRules == uidRules) return;
1367
1368 mUidRules.put(uid, uidRules);
1369 }
1370
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001371 // TODO: notify UID when it has requested targeted updates
1372 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001373
1374 @Override
1375 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001376 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001377 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001378 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001379 }
1380
1381 synchronized (mRulesLock) {
1382 mMeteredIfaces.clear();
1383 for (String iface : meteredIfaces) {
1384 mMeteredIfaces.add(iface);
1385 }
1386 }
1387 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001388
1389 @Override
1390 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1391 // caller is NPMS, since we only register with them
1392 if (LOGD_RULES) {
1393 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1394 }
1395
1396 // kick off connectivity change broadcast for active network, since
1397 // global background policy change is radical.
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001398 // TODO: Dead code; remove.
1399 //
1400 // final int networkType = mActiveDefaultNetwork;
1401 // if (isNetworkTypeValid(networkType)) {
1402 // final NetworkStateTracker tracker = mNetTrackers[networkType];
1403 // if (tracker != null) {
1404 // final NetworkInfo info = tracker.getNetworkInfo();
1405 // if (info != null && info.isConnected()) {
1406 // sendConnectedBroadcast(info);
1407 // }
1408 // }
1409 // }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001410 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001411 };
1412
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001413 private void enforceInternetPermission() {
1414 mContext.enforceCallingOrSelfPermission(
1415 android.Manifest.permission.INTERNET,
1416 "ConnectivityService");
1417 }
1418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001420 mContext.enforceCallingOrSelfPermission(
1421 android.Manifest.permission.ACCESS_NETWORK_STATE,
1422 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
1424
1425 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001426 mContext.enforceCallingOrSelfPermission(
1427 android.Manifest.permission.CHANGE_NETWORK_STATE,
1428 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
1430
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001431 private void enforceTetherAccessPermission() {
1432 mContext.enforceCallingOrSelfPermission(
1433 android.Manifest.permission.ACCESS_NETWORK_STATE,
1434 "ConnectivityService");
1435 }
1436
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001437 private void enforceConnectivityInternalPermission() {
1438 mContext.enforceCallingOrSelfPermission(
1439 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1440 "ConnectivityService");
1441 }
1442
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001443 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001444 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001445 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1446 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001447 }
1448
1449 private void sendInetConditionBroadcast(NetworkInfo info) {
1450 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1451 }
1452
Wink Saville628b0852011-08-04 15:01:58 -07001453 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001454 if (mLockdownTracker != null) {
1455 info = mLockdownTracker.augmentNetworkInfo(info);
1456 }
1457
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001458 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001459 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001460 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 if (info.isFailover()) {
1462 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1463 info.setFailover(false);
1464 }
1465 if (info.getReason() != null) {
1466 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1467 }
1468 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001469 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1470 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001472 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001473 return intent;
1474 }
1475
1476 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1477 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1478 }
1479
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001480 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001481 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1482 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1483 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001484 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001485 final long ident = Binder.clearCallingIdentity();
1486 try {
1487 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1488 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1489 } finally {
1490 Binder.restoreCallingIdentity(ident);
1491 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001492 }
1493
Mike Lockwood0f79b542009-08-14 14:18:49 -04001494 private void sendStickyBroadcast(Intent intent) {
1495 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001496 if (!mSystemReady) {
1497 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001498 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001499 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001500 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001501 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001502 }
1503
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001504 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001505 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1506 final IBatteryStats bs = BatteryStatsService.getService();
1507 try {
1508 NetworkInfo ni = intent.getParcelableExtra(
1509 ConnectivityManager.EXTRA_NETWORK_INFO);
1510 bs.noteConnectivityChanged(intent.getIntExtra(
1511 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1512 ni != null ? ni.getState().toString() : "?");
1513 } catch (RemoteException e) {
1514 }
1515 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001516 try {
1517 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1518 } finally {
1519 Binder.restoreCallingIdentity(ident);
1520 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001521 }
1522 }
1523
1524 void systemReady() {
Robert Greenwaltf9b5c262014-07-27 09:41:34 -07001525 // start network sampling ..
1526 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
1527 intent.setPackage(mContext.getPackageName());
1528
1529 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
1530 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
1531 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
1532
Wink Saville948282b2013-08-29 08:55:16 -07001533 loadGlobalProxy();
1534
Mike Lockwood0f79b542009-08-14 14:18:49 -04001535 synchronized(this) {
1536 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001537 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001538 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001539 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001540 }
1541 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001542 // load the global proxy at startup
1543 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001544
1545 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1546 // for user to unlock device.
1547 if (!updateLockdownVpn()) {
1548 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1549 mContext.registerReceiver(mUserPresentReceiver, filter);
1550 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001551
1552 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001553
1554 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 }
1556
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001557 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1558 @Override
1559 public void onReceive(Context context, Intent intent) {
1560 // Try creating lockdown tracker, since user present usually means
1561 // unlocked keystore.
1562 if (updateLockdownVpn()) {
1563 mContext.unregisterReceiver(this);
1564 }
1565 }
1566 };
1567
Wink Savilled747cbc2013-08-07 16:22:47 -07001568 /** @hide */
1569 @Override
1570 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1571 enforceConnectivityInternalPermission();
1572 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001573// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
Wink Savilled747cbc2013-08-07 16:22:47 -07001574 }
1575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001577 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001578 *
1579 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001580 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001581 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001582 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1583 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001584
1585 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001586 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001587
Robert Greenwalt7b816022014-04-18 15:25:25 -07001588 if (networkAgent.networkCapabilities.hasTransport(
1589 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001590 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1591 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001592 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001593 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001594 } else if (networkAgent.networkCapabilities.hasTransport(
1595 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001596 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1597 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07001598 0);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001599 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001600 } else {
1601 // do not track any other networks
1602 timeout = 0;
1603 }
1604
Robert Greenwalt7b816022014-04-18 15:25:25 -07001605 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001606 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001607 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001608 } catch (Exception e) {
1609 // You shall not crash!
1610 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001611 }
1612 }
1613 }
1614
1615 /**
1616 * Remove data activity tracking when network disconnects.
1617 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001618 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1619 final String iface = networkAgent.linkProperties.getInterfaceName();
1620 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001621
Robert Greenwalt7b816022014-04-18 15:25:25 -07001622 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1623 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001624 try {
1625 // the call fails silently if no idletimer setup for this interface
1626 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001627 } catch (Exception e) {
1628 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001629 }
1630 }
1631 }
1632
1633 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001634 * Reads the network specific MTU size from reources.
1635 * and set it on it's iface.
1636 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001637 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1638 final String iface = newLp.getInterfaceName();
1639 final int mtu = newLp.getMtu();
1640 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1641 if (VDBG) log("identical MTU - not setting");
1642 return;
1643 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001644
Robert Greenwalt43074032014-08-15 17:53:05 -07001645 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001646 loge("Unexpected mtu value: " + mtu + ", " + iface);
1647 return;
1648 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001649
w1997615afd812014-08-05 15:18:11 -07001650 // Cannot set MTU without interface name
1651 if (TextUtils.isEmpty(iface)) {
1652 loge("Setting MTU size with null iface.");
1653 return;
1654 }
1655
Robert Greenwalt7b816022014-04-18 15:25:25 -07001656 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001657 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001658 mNetd.setMtu(iface, mtu);
1659 } catch (Exception e) {
1660 Slog.e(TAG, "exception in setMtu()" + e);
1661 }
1662 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001663
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001664 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Irfan Sheriffd649c122010-06-09 15:39:36 -07001665
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001666 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1667 if (isDefaultNetwork(nai) == false) {
1668 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001669 }
1670
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001671 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1672 String[] values = null;
1673 if (tcpBufferSizes != null) {
1674 values = tcpBufferSizes.split(",");
1675 }
1676
1677 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001678 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001679 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1680 values = tcpBufferSizes.split(",");
1681 }
1682
1683 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1684
1685 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001686 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001687
1688 final String prefix = "/sys/kernel/ipv4/tcp_";
1689 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1690 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1691 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1692 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1693 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1694 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1695 mCurrentTcpBufferSizes = tcpBufferSizes;
1696 } catch (IOException e) {
1697 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001698 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001699
1700 final String defaultRwndKey = "net.tcp.default_init_rwnd";
1701 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
1702 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1703 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
1704 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1705 if (rwndValue != 0) {
1706 SystemProperties.set(sysctlKey, rwndValue.toString());
1707 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001708 }
1709
Mattias Falk8b47b362011-08-23 14:15:13 +02001710 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001711 /*
1712 * Tell the VMs to toss their DNS caches
1713 */
1714 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1715 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001716 /*
1717 * Connectivity events can happen before boot has completed ...
1718 */
1719 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001720 final long ident = Binder.clearCallingIdentity();
1721 try {
1722 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1723 } finally {
1724 Binder.restoreCallingIdentity(ident);
1725 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001726 }
1727
Robert Greenwalt562cc542014-05-15 18:07:26 -07001728 @Override
1729 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001730 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1731 NETWORK_RESTORE_DELAY_PROP_NAME);
1732 if(restoreDefaultNetworkDelayStr != null &&
1733 restoreDefaultNetworkDelayStr.length() != 0) {
1734 try {
1735 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1736 } catch (NumberFormatException e) {
1737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001739 // if the system property isn't set, use the value for the apn type
1740 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1741
1742 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1743 (mNetConfigs[networkType] != null)) {
1744 ret = mNetConfigs[networkType].restoreTime;
1745 }
1746 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 }
1748
1749 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001750 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1751 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001752 if (mContext.checkCallingOrSelfPermission(
1753 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001755 pw.println("Permission Denial: can't dump ConnectivityService " +
1756 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1757 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 return;
1759 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001760
Robert Greenwalta67be032014-05-16 15:49:14 -07001761 pw.println("NetworkFactories for:");
1762 pw.increaseIndent();
1763 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1764 pw.println(nfi.name);
1765 }
1766 pw.decreaseIndent();
1767 pw.println();
1768
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001769 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1770 pw.print("Active default network: ");
1771 if (defaultNai == null) {
1772 pw.println("none");
1773 } else {
1774 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001776 pw.println();
1777
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001778 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001779 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001780 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1781 pw.println(nai.toString());
1782 pw.increaseIndent();
1783 pw.println("Requests:");
1784 pw.increaseIndent();
1785 for (int i = 0; i < nai.networkRequests.size(); i++) {
1786 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001787 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001788 pw.decreaseIndent();
1789 pw.println("Lingered:");
1790 pw.increaseIndent();
1791 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1792 pw.decreaseIndent();
1793 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001794 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001795 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001796 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001797
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001798 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001799 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001800 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1801 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001802 }
1803 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001804 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001805
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001806 pw.println("mLegacyTypeTracker:");
1807 pw.increaseIndent();
1808 mLegacyTypeTracker.dump(pw);
1809 pw.decreaseIndent();
1810 pw.println();
1811
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001812 synchronized (this) {
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001813 pw.println("NetworkTransitionWakeLock is currently " +
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001814 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1815 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1816 }
1817 pw.println();
1818
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001819 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001820
1821 if (mInetLog != null) {
1822 pw.println();
1823 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001824 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001825 for(int i = 0; i < mInetLog.size(); i++) {
1826 pw.println(mInetLog.get(i));
1827 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001828 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 }
1831
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001832 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001833 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001834 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001835 if (officialNai != null && officialNai.equals(nai)) return true;
1836 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001837 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001838 " - " + nai);
1839 }
1840 return false;
1841 }
1842
Paul Jensenc8b9a742014-09-30 15:37:41 -04001843 private boolean isRequest(NetworkRequest request) {
1844 return mNetworkRequests.get(request).isRequest;
1845 }
1846
Robert Greenwalt42acef32009-08-12 16:08:25 -07001847 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001848 private class NetworkStateTrackerHandler extends Handler {
1849 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001850 super(looper);
1851 }
1852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 @Override
1854 public void handleMessage(Message msg) {
1855 NetworkInfo info;
1856 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001857 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001858 handleAsyncChannelHalfConnect(msg);
1859 break;
1860 }
1861 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1862 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1863 if (nai != null) nai.asyncChannel.disconnect();
1864 break;
1865 }
1866 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1867 handleAsyncChannelDisconnected(msg);
1868 break;
1869 }
1870 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1871 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1872 if (nai == null) {
1873 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1874 } else {
1875 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001876 }
1877 break;
1878 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001879 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1880 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1881 if (nai == null) {
1882 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1883 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001884 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001885 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001886 "; created=" + nai.created);
1887 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001888 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001889 synchronized (nai) {
1890 nai.linkProperties = (LinkProperties)msg.obj;
1891 }
Paul Jenseneec75412014-08-04 12:21:19 -04001892 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001893 }
1894 break;
1895 }
1896 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1897 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1898 if (nai == null) {
1899 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1900 break;
1901 }
1902 info = (NetworkInfo) msg.obj;
1903 updateNetworkInfo(nai, info);
1904 break;
1905 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001906 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1907 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1908 if (nai == null) {
1909 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1910 break;
1911 }
1912 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001913 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001914 break;
1915 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001916 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1917 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1918 if (nai == null) {
1919 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1920 break;
1921 }
1922 try {
1923 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001924 } catch (Exception e) {
1925 // Never crash!
1926 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001927 }
1928 break;
1929 }
1930 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1931 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1932 if (nai == null) {
1933 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1934 break;
1935 }
1936 try {
1937 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001938 } catch (Exception e) {
1939 // Never crash!
1940 loge("Exception in removeVpnUidRanges: " + e);
1941 }
1942 break;
1943 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001944 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1945 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1946 if (nai == null) {
1947 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1948 break;
1949 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001950 if (nai.created && !nai.networkMisc.explicitlySelected) {
1951 loge("ERROR: created network explicitly selected.");
1952 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001953 nai.networkMisc.explicitlySelected = true;
1954 break;
1955 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001956 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001957 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001958 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_VALIDATED")) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001959 boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001960 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001961 if (valid) {
1962 if (DBG) log("Validated " + nai.name());
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001963 if (!nai.everValidated) {
1964 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001965 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1966 ReapUnvalidatedNetworks.REAP);
1967 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001968 sendUpdatedScoreToFactories(nai);
1969 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001970 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001971 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001972 // Let the NetworkAgent know the state of its network
1973 nai.asyncChannel.sendMessage(
1974 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1975 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1976 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001977 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001978 break;
1979 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001980 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001981 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001982 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1983 handleLingerComplete(nai);
1984 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001985 break;
1986 }
Paul Jensen869868be2014-05-15 10:33:05 -04001987 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001988 if (msg.arg1 == 0) {
1989 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
1990 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04001991 NetworkAgentInfo nai = null;
1992 synchronized (mNetworkForNetId) {
1993 nai = mNetworkForNetId.get(msg.arg2);
1994 }
1995 if (nai == null) {
1996 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
1997 break;
1998 }
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001999 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
2000 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04002001 }
Paul Jensen869868be2014-05-15 10:33:05 -04002002 break;
2003 }
Wink Saville948282b2013-08-29 08:55:16 -07002004 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002006 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002007
Wink Savillec9acde92011-09-21 11:05:43 -07002008 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Saville67c38212013-09-05 12:02:25 -07002009 (state == NetworkInfo.State.DISCONNECTED) ||
2010 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillec9acde92011-09-21 11:05:43 -07002011 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002012 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002013 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015
Jeff Sharkey2528b502012-11-09 15:57:02 -08002016 EventLogTags.writeConnectivityStateChanged(
2017 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002018
Robert Greenwalt7b816022014-04-18 15:25:25 -07002019 if (info.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -07002020 /**
2021 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2022 * for now its an in between network, its a network that
2023 * is actually a default network but we don't want it to be
2024 * announced as such to keep background applications from
2025 * trying to use it. It turns out that some still try so we
2026 * take the additional step of clearing any default routes
2027 * to the link that may have incorrectly setup by the lower
2028 * levels.
2029 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002030 LinkProperties lp = getLinkPropertiesForType(info.getType());
Wink Saville948282b2013-08-29 08:55:16 -07002031 if (DBG) {
2032 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2033 }
2034
2035 // Clear any default routes setup by the radio so
2036 // any activity by applications trying to use this
2037 // connection will fail until the provisioning network
2038 // is enabled.
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002039 /*
Wink Saville948282b2013-08-29 08:55:16 -07002040 for (RouteInfo r : lp.getRoutes()) {
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07002041 removeRoute(lp, r, TO_DEFAULT_TABLE,
2042 mNetTrackers[info.getType()].getNetwork().netId);
Wink Saville948282b2013-08-29 08:55:16 -07002043 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002044 */
Robert Greenwalt511288a2009-12-07 11:33:18 -08002045 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt511288a2009-12-07 11:33:18 -08002046 } else if (state == NetworkInfo.State.SUSPENDED) {
Robert Greenwalt511288a2009-12-07 11:33:18 -08002047 } else if (state == NetworkInfo.State.CONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002048 // handleConnect(info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002050 notifyLockdownVpn(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 break;
Wink Saville948282b2013-08-29 08:55:16 -07002052 }
2053 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002054 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002055 // TODO: Temporary allowing network configuration
2056 // change not resetting sockets.
2057 // @see bug/4455071
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002058 /*
Robert Greenwalt7b816022014-04-18 15:25:25 -07002059 handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()],
2060 false);
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002061 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 break;
Wink Saville948282b2013-08-29 08:55:16 -07002063 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002064 }
2065 }
2066 }
2067
Paul Jensen0cc17322014-11-25 15:26:53 -05002068 // Cancel any lingering so the linger timeout doesn't teardown a network.
2069 // This should be called when a network begins satisfying a NetworkRequest.
2070 // Note: depending on what state the NetworkMonitor is in (e.g.,
2071 // if it's awaiting captive portal login, or if validation failed), this
2072 // may trigger a re-evaluation of the network.
2073 private void unlinger(NetworkAgentInfo nai) {
2074 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002075 // If network has never been validated, it cannot have been lingered, so don't bother
2076 // needlessly triggering a re-evaluation.
2077 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002078 nai.networkLingered.clear();
2079 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2080 }
2081
Robert Greenwalt7b816022014-04-18 15:25:25 -07002082 private void handleAsyncChannelHalfConnect(Message msg) {
2083 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002084 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002085 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2086 if (VDBG) log("NetworkFactory connected");
2087 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002088 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002089 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002090 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002091 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002092 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002093 }
2094 } else {
2095 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002096 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002097 }
2098 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2099 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2100 if (VDBG) log("NetworkAgent connected");
2101 // A network agent has requested a connection. Establish the connection.
2102 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2103 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2104 } else {
2105 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002106 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002107 if (nai != null) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002108 synchronized (mNetworkForNetId) {
2109 mNetworkForNetId.remove(nai.network.netId);
2110 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002111 // Just in case.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07002112 mLegacyTypeTracker.remove(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002113 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002114 }
2115 }
2116 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002117
Robert Greenwalt7b816022014-04-18 15:25:25 -07002118 private void handleAsyncChannelDisconnected(Message msg) {
2119 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2120 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002121 if (DBG) {
2122 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2123 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002124 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04002125 if (nai.created) {
2126 // Tell netd to clean up the configuration for this network
2127 // (routing rules, DNS, etc).
2128 try {
2129 mNetd.removeNetwork(nai.network.netId);
2130 } catch (Exception e) {
2131 loge("Exception removing network: " + e);
2132 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002133 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002134 // TODO - if we move the logic to the network agent (have them disconnect
2135 // because they lost all their requests or because their score isn't good)
2136 // then they would disconnect organically, report their new state and then
2137 // disconnect the channel.
2138 if (nai.networkInfo.isConnected()) {
2139 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2140 null, null);
2141 }
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002142 if (isDefaultNetwork(nai)) {
2143 mDefaultInetConditionPublished = 0;
2144 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002145 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002146 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002147 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002148 mNetworkAgentInfos.remove(msg.replyTo);
2149 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07002150 mLegacyTypeTracker.remove(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002151 synchronized (mNetworkForNetId) {
2152 mNetworkForNetId.remove(nai.network.netId);
2153 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002154 // Since we've lost the network, go through all the requests that
2155 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002156 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002157 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002158 for (int i = 0; i < nai.networkRequests.size(); i++) {
2159 NetworkRequest request = nai.networkRequests.valueAt(i);
2160 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2161 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002162 if (DBG) {
2163 log("Checking for replacement network to handle request " + request );
2164 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002165 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002166 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002167 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002168 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2169 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002170 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002171 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002172 alternative = existing;
2173 }
2174 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002175 if (alternative != null) {
2176 if (DBG) log(" found replacement in " + alternative.name());
2177 if (!toActivate.contains(alternative)) {
2178 toActivate.add(alternative);
2179 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002180 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002181 }
2182 }
2183 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2184 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002185 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002186 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002187 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002188 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002189 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002190 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2191 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002192 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002193 }
2194 }
2195
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002196 // If this method proves to be too slow then we can maintain a separate
2197 // pendingIntent => NetworkRequestInfo map.
2198 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2199 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2200 Intent intent = pendingIntent.getIntent();
2201 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2202 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2203 if (existingPendingIntent != null &&
2204 existingPendingIntent.getIntent().filterEquals(intent)) {
2205 return entry.getValue();
2206 }
2207 }
2208 return null;
2209 }
2210
2211 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2212 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2213
2214 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2215 if (existingRequest != null) { // remove the existing request.
2216 if (DBG) log("Replacing " + existingRequest.request + " with "
2217 + nri.request + " because their intents matched.");
2218 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2219 }
2220 handleRegisterNetworkRequest(msg);
2221 }
2222
Robert Greenwalt9258c642014-03-26 16:47:06 -07002223 private void handleRegisterNetworkRequest(Message msg) {
2224 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002225
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002226 mNetworkRequests.put(nri.request, nri);
2227
Paul Jensen0cc17322014-11-25 15:26:53 -05002228 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2229
Robert Greenwalt9258c642014-03-26 16:47:06 -07002230 // Check for the best currently alive network that satisfies this request
2231 NetworkAgentInfo bestNetwork = null;
2232 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002233 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002234 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002235 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002236 if (!nri.isRequest) {
2237 // Not setting bestNetwork here as a listening NetworkRequest may be
2238 // satisfied by multiple Networks. Instead the request is added to
2239 // each satisfying Network and notified about each.
2240 network.addRequest(nri.request);
2241 notifyNetworkCallback(network, nri);
2242 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002243 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002244 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002245 }
2246 }
2247 }
2248 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002249 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002250 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002251 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002252 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002253 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002254 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002255 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2256 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002257 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002258
Lorenzo Colittia793a672014-07-31 23:20:17 +09002259 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002260 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002261 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002262 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002263 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002264 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002265 }
2266 }
2267 }
2268
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002269 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2270 int callingUid) {
2271 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2272 if (nri != null) {
2273 handleReleaseNetworkRequest(nri.request, callingUid);
2274 }
2275 }
2276
Paul Jensen99364842014-12-09 11:43:45 -05002277 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2278 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2279 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2280 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2281 private boolean unneeded(NetworkAgentInfo nai) {
2282 if (!nai.created || nai.isVPN()) return false;
2283 boolean unneeded = true;
2284 if (nai.everValidated) {
2285 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2286 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2287 try {
2288 if (isRequest(nr)) unneeded = false;
2289 } catch (Exception e) {
2290 loge("Request " + nr + " not found in mNetworkRequests.");
2291 loge(" it came from request list of " + nai.name());
2292 }
2293 }
2294 } else {
2295 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2296 // If this Network is already the highest scoring Network for a request, or if
2297 // there is hope for it to become one if it validated, then it is needed.
2298 if (nri.isRequest && nai.satisfies(nri.request) &&
2299 (nai.networkRequests.get(nri.request.requestId) != null ||
2300 // Note that this catches two important cases:
2301 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2302 // is currently satisfying the request. This is desirable when
2303 // cellular ends up validating but WiFi does not.
2304 // 2. Unvalidated WiFi will not be reaped when validated cellular
2305 // is currently satsifying the request. This is desirable when
2306 // WiFi ends up validating and out scoring cellular.
2307 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2308 nai.getCurrentScoreAsValidated())) {
2309 unneeded = false;
2310 break;
2311 }
2312 }
2313 }
2314 return unneeded;
2315 }
2316
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002317 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2318 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002319 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002320 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002321 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2322 return;
2323 }
2324 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002325 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002326 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002327 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002328 // Find all networks that are satisfying this request and remove the request
2329 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002330 // TODO - it's my understanding that for a request there is only a single
2331 // network satisfying it, so this loop is wasteful
2332 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002333 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2334 if (nai.networkRequests.get(nri.request.requestId) != null) {
2335 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002336 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002337 log(" Removing from current network " + nai.name() +
2338 ", leaving " + nai.networkRequests.size() +
2339 " requests.");
2340 }
Paul Jensen99364842014-12-09 11:43:45 -05002341 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002342 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002343 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002344 } else {
2345 // suspect there should only be one pass through here
2346 // but if any were kept do the check below
2347 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002348 }
2349 }
2350 }
2351
Robert Greenwalt51481852015-01-08 14:43:31 -08002352 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2353 if (nai != null) {
2354 mNetworkForRequestId.remove(nri.request.requestId);
2355 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002356 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002357 // that a network connected to serve it, even though the network was already
2358 // connected. Now that this request has gone away, we might have to pretend
2359 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002360 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002361 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2362 boolean doRemove = true;
2363 if (wasKept) {
2364 // check if any of the remaining requests for this network are for the
2365 // same legacy type - if so, don't remove the nai
2366 for (int i = 0; i < nai.networkRequests.size(); i++) {
2367 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2368 if (otherRequest.legacyType == nri.request.legacyType &&
2369 isRequest(otherRequest)) {
2370 if (DBG) log(" still have other legacy request - leaving");
2371 doRemove = false;
2372 }
2373 }
2374 }
2375
2376 if (doRemove) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002377 mLegacyTypeTracker.remove(nri.request.legacyType, nai);
2378 }
2379 }
2380
Robert Greenwalta67be032014-05-16 15:49:14 -07002381 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002382 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2383 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002384 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002385 } else {
2386 // listens don't have a singular affectedNetwork. Check all networks to see
2387 // if this listen request applies and remove it.
2388 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2389 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002390 }
2391 }
2392 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2393 }
2394 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002395
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002396 private class InternalHandler extends Handler {
2397 public InternalHandler(Looper looper) {
2398 super(looper);
2399 }
2400
2401 @Override
2402 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002403 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002404 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002405 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002406 String causedBy = null;
2407 synchronized (ConnectivityService.this) {
2408 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2409 mNetTransitionWakeLock.isHeld()) {
2410 mNetTransitionWakeLock.release();
2411 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002412 } else {
2413 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002414 }
2415 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002416 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2417 log("Failed to find a new network - expiring NetTransition Wakelock");
2418 } else {
2419 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2420 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002421 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002422 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002423 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002424 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002425 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002426 break;
2427 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002428 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002429 boolean met = (msg.arg1 == ENABLED);
2430 handleSetDependencyMet(msg.arg2, met);
2431 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002432 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002433 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002434 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002435 sendStickyBroadcast(intent);
2436 break;
2437 }
Wink Savilleab9321d2013-06-29 21:10:57 -07002438 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2439 int tag = mEnableFailFastMobileDataTag.get();
2440 if (msg.arg1 == tag) {
2441 MobileDataStateTracker mobileDst =
2442 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2443 if (mobileDst != null) {
2444 mobileDst.setEnableFailFastMobileData(msg.arg2);
2445 }
2446 } else {
2447 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2448 + " != tag:" + tag);
2449 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002450 break;
Wink Savilleab9321d2013-06-29 21:10:57 -07002451 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002452 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07002453 handleNetworkSamplingTimeout();
2454 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002455 }
Jason Monkdecd2952013-10-10 14:02:51 -04002456 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002457 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002458 break;
2459 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002460 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002461 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2462 break;
2463 }
2464 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2465 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002466 break;
2467 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002468 case EVENT_REGISTER_NETWORK_AGENT: {
2469 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2470 break;
2471 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002472 case EVENT_REGISTER_NETWORK_REQUEST:
2473 case EVENT_REGISTER_NETWORK_LISTENER: {
2474 handleRegisterNetworkRequest(msg);
2475 break;
2476 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002477 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2478 handleRegisterNetworkRequestWithIntent(msg);
2479 break;
2480 }
2481 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2482 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2483 break;
2484 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002485 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002486 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002487 break;
2488 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002489 case EVENT_SYSTEM_READY: {
2490 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2491 nai.networkMonitor.systemReady = true;
2492 }
2493 break;
2494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 }
2496 }
2497 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002498
2499 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002500 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002501 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002502 if (isTetheringSupported()) {
2503 return mTethering.tether(iface);
2504 } else {
2505 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2506 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002507 }
2508
2509 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002510 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002511 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002512
2513 if (isTetheringSupported()) {
2514 return mTethering.untether(iface);
2515 } else {
2516 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2517 }
2518 }
2519
2520 // javadoc from interface
2521 public int getLastTetherError(String iface) {
2522 enforceTetherAccessPermission();
2523
2524 if (isTetheringSupported()) {
2525 return mTethering.getLastTetherError(iface);
2526 } else {
2527 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2528 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002529 }
2530
2531 // TODO - proper iface API for selection by property, inspection, etc
2532 public String[] getTetherableUsbRegexs() {
2533 enforceTetherAccessPermission();
2534 if (isTetheringSupported()) {
2535 return mTethering.getTetherableUsbRegexs();
2536 } else {
2537 return new String[0];
2538 }
2539 }
2540
2541 public String[] getTetherableWifiRegexs() {
2542 enforceTetherAccessPermission();
2543 if (isTetheringSupported()) {
2544 return mTethering.getTetherableWifiRegexs();
2545 } else {
2546 return new String[0];
2547 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002548 }
2549
Danica Chang6fdd0c62010-08-11 14:54:43 -07002550 public String[] getTetherableBluetoothRegexs() {
2551 enforceTetherAccessPermission();
2552 if (isTetheringSupported()) {
2553 return mTethering.getTetherableBluetoothRegexs();
2554 } else {
2555 return new String[0];
2556 }
2557 }
2558
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002559 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002560 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002561 if (isTetheringSupported()) {
2562 return mTethering.setUsbTethering(enable);
2563 } else {
2564 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2565 }
2566 }
2567
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002568 // TODO - move iface listing, queries, etc to new module
2569 // javadoc from interface
2570 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002571 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002572 return mTethering.getTetherableIfaces();
2573 }
2574
2575 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002576 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002577 return mTethering.getTetheredIfaces();
2578 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002579
Robert Greenwalt5a735062010-03-02 17:25:02 -08002580 public String[] getTetheringErroredIfaces() {
2581 enforceTetherAccessPermission();
2582 return mTethering.getErroredIfaces();
2583 }
2584
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002585 public String[] getTetheredDhcpRanges() {
2586 enforceConnectivityInternalPermission();
2587 return mTethering.getTetheredDhcpRanges();
2588 }
2589
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002590 // if ro.tether.denied = true we default to no tethering
2591 // gservices could set the secure setting to 1 though to enable it on a build where it
2592 // had previously been turned off.
2593 public boolean isTetheringSupported() {
2594 enforceTetherAccessPermission();
2595 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002596 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002597 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2598 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002599 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2600 mTethering.getTetherableWifiRegexs().length != 0 ||
2601 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2602 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002603 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002604
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002605 // Called when we lose the default network and have no replacement yet.
2606 // This will automatically be cleared after X seconds or a new default network
2607 // becomes CONNECTED, whichever happens first. The timer is started by the
2608 // first caller and not restarted by subsequent callers.
2609 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002610 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002611 synchronized (this) {
2612 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002613 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002614 mNetTransitionWakeLock.acquire();
2615 mNetTransitionWakeLockCausedBy = forWhom;
2616 }
2617 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002618 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002619 mNetTransitionWakeLockTimeout);
2620 return;
2621 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002622
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002623 // 100 percent is full good, 0 is full bad.
2624 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002625 if (percentage > 50) return; // don't handle good network reports
2626 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2627 if (nai != null) reportBadNetwork(nai.network);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002628 }
2629
Robert Greenwalt9258c642014-03-26 16:47:06 -07002630 public void reportBadNetwork(Network network) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002631 enforceAccessPermission();
2632 enforceInternetPermission();
2633
2634 if (network == null) return;
2635
2636 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002637 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002638 if (nai == null) return;
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002639 if (DBG) log("reportBadNetwork(" + nai.name() + ") by " + uid);
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002640 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002641 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2642 // which isn't meant to work on uncreated networks.
2643 if (!nai.created) return;
2644
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002645 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002646
2647 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2648 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002649 }
2650
Paul Jensene0bef712014-12-10 15:12:18 -05002651 public ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002652 // this information is already available as a world read/writable jvm property
2653 // so this API change wouldn't have a benifit. It also breaks the passing
2654 // of proxy info to all the JVMs.
2655 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002656 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002657 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002658 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2659 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002660 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002661 }
2662
Paul Jensene0bef712014-12-10 15:12:18 -05002663 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2664 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2665 // proxy is null then there is no proxy in place).
2666 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2667 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2668 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2669 proxy = null;
2670 }
2671 return proxy;
2672 }
2673
2674 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2675 // better for determining if a new proxy broadcast is necessary:
2676 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2677 // avoid unnecessary broadcasts.
2678 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2679 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2680 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2681 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2682 // all set.
2683 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2684 a = canonicalizeProxyInfo(a);
2685 b = canonicalizeProxyInfo(b);
2686 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2687 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2688 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2689 }
2690
Jason Monk207900c2014-04-25 15:00:09 -04002691 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002692 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002693
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002694 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002695 if (proxyProperties == mGlobalProxy) return;
2696 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2697 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2698
2699 String host = "";
2700 int port = 0;
2701 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002702 String pacFileUrl = "";
2703 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002704 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002705 if (!proxyProperties.isValid()) {
2706 if (DBG)
2707 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2708 return;
2709 }
Jason Monk207900c2014-04-25 15:00:09 -04002710 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002711 host = mGlobalProxy.getHost();
2712 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002713 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002714 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002715 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002716 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002717 } else {
2718 mGlobalProxy = null;
2719 }
2720 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002721 final long token = Binder.clearCallingIdentity();
2722 try {
2723 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2724 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2725 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2726 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002727 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002728 } finally {
2729 Binder.restoreCallingIdentity(token);
2730 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002731
Jason Monkcf0f97a2014-10-02 15:39:38 -04002732 if (mGlobalProxy == null) {
2733 proxyProperties = mDefaultProxy;
2734 }
2735 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002736 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002737 }
2738
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002739 private void loadGlobalProxy() {
2740 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002741 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2742 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2743 String exclList = Settings.Global.getString(res,
2744 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002745 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2746 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002747 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002748 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002749 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002750 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002751 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002752 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002753 if (!proxyProperties.isValid()) {
2754 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2755 return;
2756 }
2757
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002758 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002759 mGlobalProxy = proxyProperties;
2760 }
2761 }
2762 }
2763
Jason Monk207900c2014-04-25 15:00:09 -04002764 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002765 // this information is already available as a world read/writable jvm property
2766 // so this API change wouldn't have a benifit. It also breaks the passing
2767 // of proxy info to all the JVMs.
2768 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002769 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002770 return mGlobalProxy;
2771 }
2772 }
2773
Jason Monk207900c2014-04-25 15:00:09 -04002774 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002775 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002776 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002777 proxy = null;
2778 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002779 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002780 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002781 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002782 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002783 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2784 return;
2785 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002786
2787 // This call could be coming from the PacManager, containing the port of the local
2788 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2789 // global (to get the correct local port), and send a broadcast.
2790 // TODO: Switch PacManager to have its own message to send back rather than
2791 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002792 if ((mGlobalProxy != null) && (proxy != null)
2793 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002794 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2795 mGlobalProxy = proxy;
2796 sendProxyBroadcast(mGlobalProxy);
2797 return;
2798 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002799 mDefaultProxy = proxy;
2800
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002801 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002802 if (!mDefaultProxyDisabled) {
2803 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002804 }
2805 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002806 }
2807
Paul Jensene0bef712014-12-10 15:12:18 -05002808 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2809 // This method gets called when any network changes proxy, but the broadcast only ever contains
2810 // the default proxy (even if it hasn't changed).
2811 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2812 // world where an app might be bound to a non-default network.
2813 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2814 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2815 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2816
2817 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2818 sendProxyBroadcast(getDefaultProxy());
2819 }
2820 }
2821
Robert Greenwalt434203a2010-10-11 16:00:27 -07002822 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002823 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2824 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002825 if (!TextUtils.isEmpty(proxy)) {
2826 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002827 if (data.length == 0) {
2828 return;
2829 }
2830
Robert Greenwalt434203a2010-10-11 16:00:27 -07002831 String proxyHost = data[0];
2832 int proxyPort = 8080;
2833 if (data.length > 1) {
2834 try {
2835 proxyPort = Integer.parseInt(data[1]);
2836 } catch (NumberFormatException e) {
2837 return;
2838 }
2839 }
Jason Monk207900c2014-04-25 15:00:09 -04002840 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002841 setGlobalProxy(p);
2842 }
2843 }
2844
Jason Monk207900c2014-04-25 15:00:09 -04002845 private void sendProxyBroadcast(ProxyInfo proxy) {
2846 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002847 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002848 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002849 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002850 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2851 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002852 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002853 final long ident = Binder.clearCallingIdentity();
2854 try {
2855 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2856 } finally {
2857 Binder.restoreCallingIdentity(ident);
2858 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002859 }
2860
2861 private static class SettingsObserver extends ContentObserver {
2862 private int mWhat;
2863 private Handler mHandler;
2864 SettingsObserver(Handler handler, int what) {
2865 super(handler);
2866 mHandler = handler;
2867 mWhat = what;
2868 }
2869
2870 void observe(Context context) {
2871 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002872 resolver.registerContentObserver(Settings.Global.getUriFor(
2873 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002874 }
2875
2876 @Override
2877 public void onChange(boolean selfChange) {
2878 mHandler.obtainMessage(mWhat).sendToTarget();
2879 }
2880 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002881
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002882 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002883 Slog.d(TAG, s);
2884 }
2885
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002886 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002887 Slog.e(TAG, s);
2888 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002889
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002890 private static <T> T checkNotNull(T value, String message) {
2891 if (value == null) {
2892 throw new NullPointerException(message);
2893 }
2894 return value;
2895 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002896
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002897 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002898 * Prepare for a VPN application.
Jeff Davidson9a1da682014-11-11 13:52:58 -08002899 * Permissions are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002900 * @hide
2901 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002902 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002903 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002904 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002905 int user = UserHandle.getUserId(Binder.getCallingUid());
2906 synchronized(mVpns) {
2907 return mVpns.get(user).prepare(oldPackage, newPackage);
2908 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002909 }
2910
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002911 /**
Jeff Davidson05542602014-08-11 14:07:27 -07002912 * Set whether the current VPN package has the ability to launch VPNs without
Jeff Davidson9a1da682014-11-11 13:52:58 -08002913 * user intervention. This method is used by system-privileged apps.
2914 * Permissions are checked in Vpn class.
Jeff Davidson05542602014-08-11 14:07:27 -07002915 * @hide
2916 */
2917 @Override
2918 public void setVpnPackageAuthorization(boolean authorized) {
2919 int user = UserHandle.getUserId(Binder.getCallingUid());
2920 synchronized(mVpns) {
2921 mVpns.get(user).setPackageAuthorization(authorized);
2922 }
2923 }
2924
2925 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002926 * Configure a TUN interface and return its file descriptor. Parameters
2927 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002928 * and not available in ConnectivityManager. Permissions are checked in
2929 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002930 * @hide
2931 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002932 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002933 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002934 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002935 int user = UserHandle.getUserId(Binder.getCallingUid());
2936 synchronized(mVpns) {
2937 return mVpns.get(user).establish(config);
2938 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002939 }
2940
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002941 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07002942 * Start legacy VPN, controlling native daemons as needed. Creates a
2943 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002944 */
2945 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07002946 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002947 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07002948 final LinkProperties egress = getActiveLinkProperties();
2949 if (egress == null) {
2950 throw new IllegalStateException("Missing active network connection");
2951 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002952 int user = UserHandle.getUserId(Binder.getCallingUid());
2953 synchronized(mVpns) {
2954 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
2955 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002956 }
2957
2958 /**
2959 * Return the information of the ongoing legacy VPN. This method is used
2960 * by VpnSettings and not available in ConnectivityManager. Permissions
2961 * are checked in Vpn class.
2962 * @hide
2963 */
2964 @Override
2965 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002966 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002967 int user = UserHandle.getUserId(Binder.getCallingUid());
2968 synchronized(mVpns) {
2969 return mVpns.get(user).getLegacyVpnInfo();
2970 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002971 }
2972
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002973 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07002974 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
2975 * not available in ConnectivityManager.
2976 * Permissions are checked in Vpn class.
2977 * @hide
2978 */
2979 @Override
2980 public VpnConfig getVpnConfig() {
2981 int user = UserHandle.getUserId(Binder.getCallingUid());
2982 synchronized(mVpns) {
2983 return mVpns.get(user).getVpnConfig();
2984 }
2985 }
2986
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002987 @Override
2988 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08002989 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
2990 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
2991 return false;
2992 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002993
2994 // Tear down existing lockdown if profile was removed
2995 mLockdownEnabled = LockdownVpnTracker.isEnabled();
2996 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08002997 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002998 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
2999 return false;
3000 }
3001
3002 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3003 final VpnProfile profile = VpnProfile.decode(
3004 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003005 int user = UserHandle.getUserId(Binder.getCallingUid());
3006 synchronized(mVpns) {
3007 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3008 profile));
3009 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003010 } else {
3011 setLockdownTracker(null);
3012 }
3013
3014 return true;
3015 }
3016
3017 /**
3018 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3019 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3020 */
3021 private void setLockdownTracker(LockdownVpnTracker tracker) {
3022 // Shutdown any existing tracker
3023 final LockdownVpnTracker existing = mLockdownTracker;
3024 mLockdownTracker = null;
3025 if (existing != null) {
3026 existing.shutdown();
3027 }
3028
3029 try {
3030 if (tracker != null) {
3031 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003032 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003033 mLockdownTracker = tracker;
3034 mLockdownTracker.init();
3035 } else {
3036 mNetd.setFirewallEnabled(false);
3037 }
3038 } catch (RemoteException e) {
3039 // ignored; NMS lives inside system_server
3040 }
3041 }
3042
3043 private void throwIfLockdownEnabled() {
3044 if (mLockdownEnabled) {
3045 throw new IllegalStateException("Unavailable in lockdown mode");
3046 }
3047 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003048
3049 public void supplyMessenger(int networkType, Messenger messenger) {
3050 enforceConnectivityInternalPermission();
3051
3052 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3053 mNetTrackers[networkType].supplyMessenger(messenger);
3054 }
3055 }
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07003056
3057 public int findConnectionTypeForIface(String iface) {
3058 enforceConnectivityInternalPermission();
3059
3060 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
Lorenzo Colitti1c3a35b2014-08-19 21:31:08 -07003061
3062 synchronized(mNetworkForNetId) {
3063 for (int i = 0; i < mNetworkForNetId.size(); i++) {
3064 NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
3065 LinkProperties lp = nai.linkProperties;
3066 if (lp != null && iface.equals(lp.getInterfaceName()) && nai.networkInfo != null) {
3067 return nai.networkInfo.getType();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07003068 }
3069 }
3070 }
3071 return ConnectivityManager.TYPE_NONE;
3072 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003073
3074 /**
3075 * Have mobile data fail fast if enabled.
3076 *
3077 * @param enabled DctConstants.ENABLED/DISABLED
3078 */
3079 private void setEnableFailFastMobileData(int enabled) {
3080 int tag;
3081
3082 if (enabled == DctConstants.ENABLED) {
3083 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3084 } else {
3085 tag = mEnableFailFastMobileDataTag.get();
3086 }
3087 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3088 enabled));
3089 }
3090
3091 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003092 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003093 // TODO: Remove? Any reason to trigger a provisioning check?
3094 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003095 }
3096
3097 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3098 private volatile boolean mIsNotificationVisible = false;
3099
Paul Jensen89e0f092014-09-15 15:59:36 -04003100 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003101 if (DBG) {
3102 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003103 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003104 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003105 Intent intent = new Intent(action);
3106 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003107 // Concatenate the range of types onto the range of NetIDs.
3108 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Paul Jensen89e0f092014-09-15 15:59:36 -04003109 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003110 }
3111
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003112 /**
3113 * Show or hide network provisioning notificaitons.
3114 *
3115 * @param id an identifier that uniquely identifies this notification. This must match
3116 * between show and hide calls. We use the NetID value but for legacy callers
3117 * we concatenate the range of types with the range of NetIDs.
3118 */
3119 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
Paul Jensen869868be2014-05-15 10:33:05 -04003120 String extraInfo, PendingIntent intent) {
3121 if (DBG) {
3122 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3123 networkType + " extraInfo=" + extraInfo);
3124 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003125
3126 Resources r = Resources.getSystem();
3127 NotificationManager notificationManager = (NotificationManager) mContext
3128 .getSystemService(Context.NOTIFICATION_SERVICE);
3129
3130 if (visible) {
3131 CharSequence title;
3132 CharSequence details;
3133 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07003134 Notification notification = new Notification();
3135 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003136 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003137 title = r.getString(R.string.wifi_available_sign_in, 0);
3138 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003139 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003140 icon = R.drawable.stat_notify_wifi_in_range;
3141 break;
3142 case ConnectivityManager.TYPE_MOBILE:
3143 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003144 title = r.getString(R.string.network_available_sign_in, 0);
3145 // TODO: Change this to pull from NetworkInfo once a printable
3146 // name has been added to it
3147 details = mTelephonyManager.getNetworkOperatorName();
3148 icon = R.drawable.stat_notify_rssi_in_range;
3149 break;
3150 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07003151 title = r.getString(R.string.network_available_sign_in, 0);
3152 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003153 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003154 icon = R.drawable.stat_notify_rssi_in_range;
3155 break;
3156 }
3157
Wink Savilleab9321d2013-06-29 21:10:57 -07003158 notification.when = 0;
3159 notification.icon = icon;
3160 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07003161 notification.tickerText = title;
Selim Cinek255dd042014-08-19 22:29:02 +02003162 notification.color = mContext.getResources().getColor(
3163 com.android.internal.R.color.system_notification_accent_color);
Wink Savilleab9321d2013-06-29 21:10:57 -07003164 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003165 notification.contentIntent = intent;
Wink Savilleab9321d2013-06-29 21:10:57 -07003166
Wink Saville948282b2013-08-29 08:55:16 -07003167 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003168 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003169 } catch (NullPointerException npe) {
3170 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3171 npe.printStackTrace();
3172 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003173 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003174 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003175 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003176 } catch (NullPointerException npe) {
3177 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3178 npe.printStackTrace();
3179 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003180 }
Wink Saville948282b2013-08-29 08:55:16 -07003181 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07003182 }
3183
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003184 /** Location to an updatable file listing carrier provisioning urls.
3185 * An example:
3186 *
3187 * <?xml version="1.0" encoding="utf-8"?>
3188 * <provisioningUrls>
3189 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
3190 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3191 * </provisioningUrls>
3192 */
3193 private static final String PROVISIONING_URL_PATH =
3194 "/data/misc/radio/provisioning_urls.xml";
3195 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003196
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003197 /** XML tag for root element. */
3198 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3199 /** XML tag for individual url */
3200 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3201 /** XML tag for redirected url */
3202 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3203 /** XML attribute for mcc */
3204 private static final String ATTR_MCC = "mcc";
3205 /** XML attribute for mnc */
3206 private static final String ATTR_MNC = "mnc";
3207
3208 private static final int REDIRECTED_PROVISIONING = 1;
3209 private static final int PROVISIONING = 2;
3210
3211 private String getProvisioningUrlBaseFromFile(int type) {
3212 FileReader fileReader = null;
3213 XmlPullParser parser = null;
3214 Configuration config = mContext.getResources().getConfiguration();
3215 String tagType;
3216
3217 switch (type) {
3218 case PROVISIONING:
3219 tagType = TAG_PROVISIONING_URL;
3220 break;
3221 case REDIRECTED_PROVISIONING:
3222 tagType = TAG_REDIRECTED_URL;
3223 break;
3224 default:
3225 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3226 type);
3227 }
3228
3229 try {
3230 fileReader = new FileReader(mProvisioningUrlFile);
3231 parser = Xml.newPullParser();
3232 parser.setInput(fileReader);
3233 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3234
3235 while (true) {
3236 XmlUtils.nextElement(parser);
3237
3238 String element = parser.getName();
3239 if (element == null) break;
3240
3241 if (element.equals(tagType)) {
3242 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3243 try {
3244 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3245 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3246 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3247 parser.next();
3248 if (parser.getEventType() == XmlPullParser.TEXT) {
3249 return parser.getText();
3250 }
3251 }
3252 }
3253 } catch (NumberFormatException e) {
3254 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3255 }
3256 }
3257 }
3258 return null;
3259 } catch (FileNotFoundException e) {
3260 loge("Carrier Provisioning Urls file not found");
3261 } catch (XmlPullParserException e) {
3262 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3263 } catch (IOException e) {
3264 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3265 } finally {
3266 if (fileReader != null) {
3267 try {
3268 fileReader.close();
3269 } catch (IOException e) {}
3270 }
3271 }
3272 return null;
3273 }
3274
Wink Saville42d4f082013-07-20 20:31:59 -07003275 @Override
3276 public String getMobileRedirectedProvisioningUrl() {
3277 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003278 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3279 if (TextUtils.isEmpty(url)) {
3280 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3281 }
3282 return url;
3283 }
3284
Wink Saville42d4f082013-07-20 20:31:59 -07003285 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003286 public String getMobileProvisioningUrl() {
3287 enforceConnectivityInternalPermission();
3288 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3289 if (TextUtils.isEmpty(url)) {
3290 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003291 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003292 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003293 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003294 }
Wink Saville8cf35602013-07-10 23:00:07 -07003295 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003296 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003297 String phoneNumber = mTelephonyManager.getLine1Number();
3298 if (TextUtils.isEmpty(phoneNumber)) {
3299 phoneNumber = "0000000000";
3300 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003301 url = String.format(url,
3302 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3303 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003304 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003305 }
3306
Wink Savilleab9321d2013-06-29 21:10:57 -07003307 return url;
3308 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003309
Wink Saville948282b2013-08-29 08:55:16 -07003310 @Override
3311 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003312 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003313 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003314 final long ident = Binder.clearCallingIdentity();
3315 try {
3316 setProvNotificationVisible(visible, networkType, action);
3317 } finally {
3318 Binder.restoreCallingIdentity(ident);
3319 }
Wink Saville948282b2013-08-29 08:55:16 -07003320 }
Wink Saville7788c612013-08-29 14:57:08 -07003321
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003322 @Override
3323 public void setAirplaneMode(boolean enable) {
3324 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003325 final long ident = Binder.clearCallingIdentity();
3326 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003327 final ContentResolver cr = mContext.getContentResolver();
3328 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3329 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3330 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003331 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003332 } finally {
3333 Binder.restoreCallingIdentity(ident);
3334 }
3335 }
3336
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003337 private void onUserStart(int userId) {
3338 synchronized(mVpns) {
3339 Vpn userVpn = mVpns.get(userId);
3340 if (userVpn != null) {
3341 loge("Starting user already has a VPN");
3342 return;
3343 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04003344 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, this, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003345 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003346 }
3347 }
3348
3349 private void onUserStop(int userId) {
3350 synchronized(mVpns) {
3351 Vpn userVpn = mVpns.get(userId);
3352 if (userVpn == null) {
3353 loge("Stopping user has no VPN");
3354 return;
3355 }
3356 mVpns.delete(userId);
3357 }
3358 }
3359
3360 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3361 @Override
3362 public void onReceive(Context context, Intent intent) {
3363 final String action = intent.getAction();
3364 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3365 if (userId == UserHandle.USER_NULL) return;
3366
3367 if (Intent.ACTION_USER_STARTING.equals(action)) {
3368 onUserStart(userId);
3369 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3370 onUserStop(userId);
3371 }
3372 }
3373 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003374
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003375 /* Infrastructure for network sampling */
3376
3377 private void handleNetworkSamplingTimeout() {
3378
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003379 if (SAMPLE_DBG) log("Sampling interval elapsed, updating statistics ..");
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003380
3381 // initialize list of interfaces ..
3382 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
3383 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
3384 for (NetworkStateTracker tracker : mNetTrackers) {
3385 if (tracker != null) {
3386 String ifaceName = tracker.getNetworkInterfaceName();
3387 if (ifaceName != null) {
3388 mapIfaceToSample.put(ifaceName, null);
3389 }
3390 }
3391 }
3392
3393 // Read samples for all interfaces
3394 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
3395
3396 // process samples for all networks
3397 for (NetworkStateTracker tracker : mNetTrackers) {
3398 if (tracker != null) {
3399 String ifaceName = tracker.getNetworkInterfaceName();
3400 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
3401 if (ss != null) {
3402 // end the previous sampling cycle
3403 tracker.stopSampling(ss);
3404 // start a new sampling cycle ..
3405 tracker.startSampling(ss);
3406 }
3407 }
3408 }
3409
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003410 if (SAMPLE_DBG) log("Done.");
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003411
3412 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
3413 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
3414 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
3415
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003416 if (SAMPLE_DBG) {
3417 log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
3418 }
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003419
3420 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
3421 }
3422
Aaron Whytef5e67472014-07-10 14:05:35 -07003423 /**
3424 * Sets a network sampling alarm.
3425 */
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003426 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
3427 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
Aaron Whytef5e67472014-07-10 14:05:35 -07003428 int alarmType;
3429 if (Resources.getSystem().getBoolean(
3430 R.bool.config_networkSamplingWakesDevice)) {
3431 alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
3432 } else {
3433 alarmType = AlarmManager.ELAPSED_REALTIME;
3434 }
3435 mAlarmManager.set(alarmType, wakeupTime, intent);
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003436 }
Robert Greenwalte049c232014-04-11 15:53:27 -07003437
Robert Greenwalta67be032014-05-16 15:49:14 -07003438 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3439 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003440 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3441 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003442
Robert Greenwalta67be032014-05-16 15:49:14 -07003443 private static class NetworkFactoryInfo {
3444 public final String name;
3445 public final Messenger messenger;
3446 public final AsyncChannel asyncChannel;
3447
3448 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3449 this.name = name;
3450 this.messenger = messenger;
3451 this.asyncChannel = asyncChannel;
3452 }
3453 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003454
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003455 /**
3456 * Tracks info about the requester.
3457 * Also used to notice when the calling process dies so we can self-expire
3458 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003459 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3460 static final boolean REQUEST = true;
3461 static final boolean LISTEN = false;
3462
3463 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003464 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003465 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003466 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003467 final int mPid;
3468 final int mUid;
3469 final Messenger messenger;
3470 final boolean isRequest;
3471
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003472 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3473 request = r;
3474 mPendingIntent = pi;
3475 messenger = null;
3476 mBinder = null;
3477 mPid = getCallingPid();
3478 mUid = getCallingUid();
3479 this.isRequest = isRequest;
3480 }
3481
Robert Greenwalt9258c642014-03-26 16:47:06 -07003482 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3483 super();
3484 messenger = m;
3485 request = r;
3486 mBinder = binder;
3487 mPid = getCallingPid();
3488 mUid = getCallingUid();
3489 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003490 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003491
3492 try {
3493 mBinder.linkToDeath(this, 0);
3494 } catch (RemoteException e) {
3495 binderDied();
3496 }
3497 }
3498
3499 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003500 if (mBinder != null) {
3501 mBinder.unlinkToDeath(this, 0);
3502 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003503 }
3504
3505 public void binderDied() {
3506 log("ConnectivityService NetworkRequestInfo binderDied(" +
3507 request + ", " + mBinder + ")");
3508 releaseNetworkRequest(request);
3509 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003510
3511 public String toString() {
3512 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003513 mPid + " for " + request +
3514 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003515 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003516 }
3517
3518 @Override
3519 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003520 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003521 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003522 enforceNetworkRequestPermissions(networkCapabilities);
3523 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003524
Robert Greenwalt6078b502014-06-11 16:05:07 -07003525 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003526 throw new IllegalArgumentException("Bad timeout specified");
3527 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003528
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003529 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3530 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003531 if (DBG) log("requestNetwork for " + networkRequest);
3532 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3533 NetworkRequestInfo.REQUEST);
3534
3535 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003536 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003537 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003538 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003539 }
3540 return networkRequest;
3541 }
3542
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003543 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3544 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
3545 == false) {
3546 enforceConnectivityInternalPermission();
3547 } else {
3548 enforceChangePermission();
3549 }
3550 }
3551
3552 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3553 // if UID is restricted, don't allow them to bring up metered APNs
3554 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
3555 == false) {
3556 final int uidRules;
3557 final int uid = Binder.getCallingUid();
3558 synchronized(mRulesLock) {
3559 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3560 }
3561 if ((uidRules & RULE_REJECT_METERED) != 0) {
3562 // we could silently fail or we can filter the available nets to only give
3563 // them those they have access to. Chose the more useful
3564 networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3565 }
3566 }
3567 }
3568
Robert Greenwalt9258c642014-03-26 16:47:06 -07003569 @Override
3570 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3571 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003572 checkNotNull(operation, "PendingIntent cannot be null.");
3573 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3574 enforceNetworkRequestPermissions(networkCapabilities);
3575 enforceMeteredApnPolicy(networkCapabilities);
3576
3577 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3578 nextNetworkRequestId());
3579 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3580 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3581 NetworkRequestInfo.REQUEST);
3582 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3583 nri));
3584 return networkRequest;
3585 }
3586
Jeremy Joslin79294842014-12-03 17:15:28 -08003587 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3588 mHandler.sendMessageDelayed(
3589 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3590 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3591 }
3592
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003593 @Override
3594 public void releasePendingNetworkRequest(PendingIntent operation) {
3595 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3596 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003597 }
3598
3599 @Override
3600 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3601 Messenger messenger, IBinder binder) {
3602 enforceAccessPermission();
3603
3604 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003605 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003606 if (DBG) log("listenForNetwork for " + networkRequest);
3607 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3608 NetworkRequestInfo.LISTEN);
3609
3610 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3611 return networkRequest;
3612 }
3613
3614 @Override
3615 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3616 PendingIntent operation) {
3617 }
3618
3619 @Override
3620 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003621 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3622 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003623 }
3624
3625 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003626 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003627 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003628 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3629 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003630 }
3631
Robert Greenwalta67be032014-05-16 15:49:14 -07003632 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003633 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003634 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3635 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3636 }
3637
3638 @Override
3639 public void unregisterNetworkFactory(Messenger messenger) {
3640 enforceConnectivityInternalPermission();
3641 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3642 }
3643
3644 private void handleUnregisterNetworkFactory(Messenger messenger) {
3645 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3646 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003647 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003648 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003649 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003650 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003651 }
3652
Robert Greenwalt7b816022014-04-18 15:25:25 -07003653 /**
3654 * NetworkAgentInfo supporting a request by requestId.
3655 * These have already been vetted (their Capabilities satisfy the request)
3656 * and the are the highest scored network available.
3657 * the are keyed off the Requests requestId.
3658 */
3659 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3660 new SparseArray<NetworkAgentInfo>();
3661
Robert Greenwalt9258c642014-03-26 16:47:06 -07003662 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3663 new SparseArray<NetworkAgentInfo>();
3664
Robert Greenwalt7b816022014-04-18 15:25:25 -07003665 // NetworkAgentInfo keyed off its connecting messenger
3666 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
3667 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3668 new HashMap<Messenger, NetworkAgentInfo>();
3669
Paul Jensen2c311d62014-11-17 12:34:51 -05003670 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003671 private final NetworkRequest mDefaultRequest;
3672
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003673 private NetworkAgentInfo getDefaultNetwork() {
3674 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3675 }
3676
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003677 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003678 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003679 }
3680
Robert Greenwalt7b816022014-04-18 15:25:25 -07003681 public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
3682 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003683 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003684 enforceConnectivityInternalPermission();
3685
Paul Jensen2c311d62014-11-17 12:34:51 -05003686 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3687 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003688 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Robert Greenwalt7b816022014-04-18 15:25:25 -07003689 new NetworkInfo(networkInfo), new LinkProperties(linkProperties),
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003690 new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler,
Paul Jensen2c311d62014-11-17 12:34:51 -05003691 new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003692 synchronized (this) {
3693 nai.networkMonitor.systemReady = mSystemReady;
3694 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003695 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003696 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
3697 }
3698
3699 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3700 if (VDBG) log("Got NetworkAgent Messenger");
3701 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen60061a62014-08-05 14:13:48 -04003702 assignNextNetId(na);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003703 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3704 NetworkInfo networkInfo = na.networkInfo;
3705 na.networkInfo = null;
3706 updateNetworkInfo(na, networkInfo);
3707 }
3708
3709 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3710 LinkProperties newLp = networkAgent.linkProperties;
3711 int netId = networkAgent.network.netId;
3712
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003713 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3714 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003715 if (networkAgent.clatd != null) {
3716 networkAgent.clatd.fixupLinkProperties(oldLp);
3717 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003718
Paul Jensen992f2522014-04-28 10:33:11 -04003719 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003720 updateMtu(newLp, oldLp);
3721 // TODO - figure out what to do for clat
3722// for (LinkProperties lp : newLp.getStackedLinks()) {
3723// updateMtu(lp, null);
3724// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003725 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003726
3727 // TODO: deprecate and remove mDefaultDns when we can do so safely.
3728 // For now, use it only when the network has Internet access. http://b/18327075
3729 final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3730 NetworkCapabilities.NET_CAPABILITY_INTERNET);
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003731 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003732 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3733
Paul Jensen3b759822014-05-13 11:44:01 -04003734 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003735 if (isDefaultNetwork(networkAgent)) {
3736 handleApplyDefaultProxy(newLp.getHttpProxy());
3737 } else {
3738 updateProxy(newLp, oldLp, networkAgent);
3739 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003740 // TODO - move this check to cover the whole function
3741 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003742 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003743 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3744 }
Paul Jensen3b759822014-05-13 11:44:01 -04003745 }
3746
Lorenzo Colitti95439462014-10-09 13:44:48 +09003747 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3748 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3749 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003750
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003751 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003752 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3753 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003754 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003755 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003756 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003757 }
Paul Jensen992f2522014-04-28 10:33:11 -04003758
3759 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3760 CompareResult<String> interfaceDiff = new CompareResult<String>();
3761 if (oldLp != null) {
3762 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3763 } else if (newLp != null) {
3764 interfaceDiff.added = newLp.getAllInterfaceNames();
3765 }
3766 for (String iface : interfaceDiff.added) {
3767 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003768 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003769 mNetd.addInterfaceToNetwork(iface, netId);
3770 } catch (Exception e) {
3771 loge("Exception adding interface: " + e);
3772 }
3773 }
3774 for (String iface : interfaceDiff.removed) {
3775 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003776 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003777 mNetd.removeInterfaceFromNetwork(iface, netId);
3778 } catch (Exception e) {
3779 loge("Exception removing interface: " + e);
3780 }
3781 }
3782 }
3783
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003784 /**
3785 * Have netd update routes from oldLp to newLp.
3786 * @return true if routes changed between oldLp and newLp
3787 */
3788 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003789 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3790 if (oldLp != null) {
3791 routeDiff = oldLp.compareAllRoutes(newLp);
3792 } else if (newLp != null) {
3793 routeDiff.added = newLp.getAllRoutes();
3794 }
3795
3796 // add routes before removing old in case it helps with continuous connectivity
3797
3798 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3799 for (RouteInfo route : routeDiff.added) {
3800 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003801 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003802 try {
3803 mNetd.addRoute(netId, route);
3804 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003805 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3806 loge("Exception in addRoute for non-gateway: " + e);
3807 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003808 }
3809 }
3810 for (RouteInfo route : routeDiff.added) {
3811 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003812 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003813 try {
3814 mNetd.addRoute(netId, route);
3815 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003816 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3817 loge("Exception in addRoute for gateway: " + e);
3818 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003819 }
3820 }
3821
3822 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003823 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003824 try {
3825 mNetd.removeRoute(netId, route);
3826 } catch (Exception e) {
3827 loge("Exception in removeRoute: " + e);
3828 }
3829 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003830 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003831 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003832 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3833 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003834 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Robert Greenwaltdf2b8782014-06-06 10:30:11 -07003835 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003836 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003837 dnses = new ArrayList();
3838 dnses.add(mDefaultDns);
3839 if (DBG) {
3840 loge("no dns provided for netId " + netId + ", so using defaults");
3841 }
3842 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003843 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003844 try {
3845 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3846 newLp.getDomains());
3847 } catch (Exception e) {
3848 loge("Exception in setDnsServersForNetwork: " + e);
3849 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003850 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3851 if (defaultNai != null && defaultNai.network.netId == netId) {
3852 setDefaultDnsSystemProperties(dnses);
3853 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003854 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003855 } else if (flush) {
3856 try {
3857 mNetd.flushNetworkDnsCache(netId);
3858 } catch (Exception e) {
3859 loge("Exception in flushNetworkDnsCache: " + e);
3860 }
3861 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003862 }
3863 }
3864
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003865 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3866 int last = 0;
3867 for (InetAddress dns : dnses) {
3868 ++last;
3869 String key = "net.dns" + last;
3870 String value = dns.getHostAddress();
3871 SystemProperties.set(key, value);
3872 }
3873 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3874 String key = "net.dns" + i;
3875 SystemProperties.set(key, "");
3876 }
3877 mNumDnsEntries = last;
3878 }
3879
Robert Greenwalt7b816022014-04-18 15:25:25 -07003880 private void updateCapabilities(NetworkAgentInfo networkAgent,
3881 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003882 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
3883 synchronized (networkAgent) {
3884 networkAgent.networkCapabilities = networkCapabilities;
3885 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08003886 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003887 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07003888 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003889 }
3890
Paul Jensenc8b9a742014-09-30 15:37:41 -04003891 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
3892 for (int i = 0; i < nai.networkRequests.size(); i++) {
3893 NetworkRequest nr = nai.networkRequests.valueAt(i);
3894 // Don't send listening requests to factories. b/17393458
3895 if (!isRequest(nr)) continue;
3896 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
3897 }
3898 }
3899
Robert Greenwalt7b816022014-04-18 15:25:25 -07003900 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
3901 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07003902 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07003903 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
3904 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003905 }
3906 }
3907
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003908 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
3909 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08003910 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003911 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08003912 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
3913 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08003914 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003915 sendIntent(nri.mPendingIntent, intent);
3916 }
3917 // else not handled
3918 }
3919
3920 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
3921 mPendingIntentWakeLock.acquire();
3922 try {
3923 if (DBG) log("Sending " + pendingIntent);
3924 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
3925 } catch (PendingIntent.CanceledException e) {
3926 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
3927 mPendingIntentWakeLock.release();
3928 releasePendingNetworkRequest(pendingIntent);
3929 }
3930 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
3931 }
3932
3933 @Override
3934 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
3935 String resultData, Bundle resultExtras) {
3936 if (DBG) log("Finished sending " + pendingIntent);
3937 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08003938 // Release with a delay so the receiving client has an opportunity to put in its
3939 // own request.
3940 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003941 }
3942
Robert Greenwalt9258c642014-03-26 16:47:06 -07003943 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003944 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003945 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003946 Bundle bundle = new Bundle();
3947 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
3948 new NetworkRequest(nri.request));
3949 Message msg = Message.obtain();
3950 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
3951 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
3952 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
3953 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003954 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003955 case ConnectivityManager.CALLBACK_LOSING: {
3956 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
3957 break;
3958 }
3959 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
3960 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
3961 new NetworkCapabilities(networkAgent.networkCapabilities));
3962 break;
3963 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003964 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003965 bundle.putParcelable(LinkProperties.class.getSimpleName(),
3966 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003967 break;
3968 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003969 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003970 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003971 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003972 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003973 if (VDBG) {
3974 log("sending notification " + notifyTypeToName(notificationType) +
3975 " for " + nri.request);
3976 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003977 nri.messenger.send(msg);
3978 } catch (RemoteException e) {
3979 // may occur naturally in the race of binder death.
3980 loge("RemoteException caught trying to send a callback msg for " + nri.request);
3981 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003982 }
3983
Paul Jensenc8b9a742014-09-30 15:37:41 -04003984 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
3985 for (int i = 0; i < nai.networkRequests.size(); i++) {
3986 NetworkRequest nr = nai.networkRequests.valueAt(i);
3987 // Ignore listening requests.
3988 if (!isRequest(nr)) continue;
3989 loge("Dead network still had at least " + nr);
3990 break;
3991 }
3992 nai.asyncChannel.disconnect();
3993 }
3994
Robert Greenwalt7b816022014-04-18 15:25:25 -07003995 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
3996 if (oldNetwork == null) {
3997 loge("Unknown NetworkAgentInfo in handleLingerComplete");
3998 return;
3999 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004000 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4001 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004002 }
4003
Paul Jensen27b02b72014-07-14 12:03:33 -04004004 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004005 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004006 setupDataActivityTracking(newNetwork);
4007 try {
4008 mNetd.setDefaultNetId(newNetwork.network.netId);
4009 } catch (Exception e) {
4010 loge("Exception setting default network :" + e);
4011 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004012 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004013 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004014 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004015 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004016 }
4017
Paul Jensen2161a8e2014-09-11 11:00:39 -04004018 // Handles a network appearing or improving its score.
4019 //
4020 // - Evaluates all current NetworkRequests that can be
4021 // satisfied by newNetwork, and reassigns to newNetwork
4022 // any such requests for which newNetwork is the best.
4023 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004024 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004025 // needed. A network is needed if it is the best network for
4026 // one or more NetworkRequests, or if it is a VPN.
4027 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004028 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004029 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4030 //
4031 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4032 // networks that have no chance (i.e. even if validated)
4033 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004034 //
4035 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4036 // it does not remove NetworkRequests that other Networks could better satisfy.
4037 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4038 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4039 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004040 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004041 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004042 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004043 // torn down if unneeded.
4044 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4045 // performed to tear down unvalidated networks that have no chance (i.e. even if
4046 // validated) of becoming the highest scoring network.
4047 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4048 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004049 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004050 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004051 loge("ERROR: nascent network not validated.");
4052 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004053 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004054 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004055 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004056 if (DBG) log("rematching " + newNetwork.name());
4057 // Find and migrate to this Network any NetworkRequests for
4058 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004059 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004060 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004061 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004062 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4063 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004064 if (DBG) {
4065 log("Network " + newNetwork.name() + " was already satisfying" +
4066 " request " + nri.request.requestId + ". No change.");
4067 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004068 keep = true;
4069 continue;
4070 }
4071
4072 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004073 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004074 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004075 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004076 // This is not a request, it's a callback listener.
4077 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04004078 newNetwork.addRequest(nri.request);
4079 continue;
4080 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004081
Robert Greenwalt7b816022014-04-18 15:25:25 -07004082 // next check if it's better than any current network we're using for
4083 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004084 if (VDBG) {
4085 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004086 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4087 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004088 }
4089 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004090 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004091 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004092 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004093 currentNetwork.networkRequests.remove(nri.request.requestId);
4094 currentNetwork.networkLingered.add(nri.request);
4095 affectedNetworks.add(currentNetwork);
4096 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004097 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004098 }
Paul Jensen573a0352015-01-08 10:49:34 -05004099 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004100 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07004101 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004102 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004103 // Tell NetworkFactories about the new score, so they can stop
4104 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004105 // TODO - this could get expensive if we have alot of requests for this
4106 // network. Think about if there is a way to reduce this. Push
4107 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004108 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004109 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004110 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004111 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004112 }
4113 }
4114 }
4115 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004116 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004117 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004118 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004119 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4120 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4121 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004122 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004123 }
4124 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004125 if (keep) {
4126 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004127 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004128 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004129 synchronized (ConnectivityService.this) {
4130 // have a new default network, release the transition wakelock in
4131 // a second if it's held. The second pause is to allow apps
4132 // to reconnect over the new network
4133 if (mNetTransitionWakeLock.isHeld()) {
4134 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4135 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4136 mNetTransitionWakeLockSerialNumber, 0),
4137 1000);
4138 }
4139 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004140 }
4141
4142 // do this after the default net is switched, but
4143 // before LegacyTypeTracker sends legacy broadcasts
4144 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4145
4146 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004147 // Maintain the illusion: since the legacy API only
4148 // understands one network at a time, we must pretend
4149 // that the current default network disconnected before
4150 // the new one connected.
4151 if (oldDefaultNetwork != null) {
4152 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4153 oldDefaultNetwork);
4154 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004155 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004156 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4157 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004158 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004159
4160 // Notify battery stats service about this network, both the normal
4161 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004162 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004163 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004164 final IBatteryStats bs = BatteryStatsService.getService();
4165 final int type = newNetwork.networkInfo.getType();
4166
4167 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4168 bs.noteNetworkInterfaceType(baseIface, type);
4169 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4170 final String stackedIface = stacked.getInterfaceName();
4171 bs.noteNetworkInterfaceType(stackedIface, type);
4172 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4173 }
4174 } catch (RemoteException ignored) {
4175 }
4176
Robert Greenwalt152ed372014-12-17 17:19:53 -08004177 // This has to happen after the notifyNetworkCallbacks as that tickles each
4178 // ConnectivityManager instance so that legacy requests correctly bind dns
4179 // requests to this network. The legacy users are listening for this bcast
4180 // and will generally do a dns request so they can ensureRouteToHost and if
4181 // they do that before the callbacks happen they'll use the default network.
4182 //
4183 // TODO: Is there still a race here? We send the broadcast
4184 // after sending the callback, but if the app can receive the
4185 // broadcast before the callback, it might still break.
4186 //
4187 // This *does* introduce a race where if the user uses the new api
4188 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4189 // they may get old info. Reverse this after the old startUsing api is removed.
4190 // This is on top of the multiple intent sequencing referenced in the todo above.
4191 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4192 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4193 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4194 // legacy type tracker filters out repeat adds
4195 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4196 }
4197 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004198
4199 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4200 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4201 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4202 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4203 if (newNetwork.isVPN()) {
4204 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4205 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004206 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004207 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004208 // validated (and get evaluated against peers, one losing here), or get reaped (see
4209 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4210 // network. Networks that have been up for a while and are validated should be torn
4211 // down via the lingering process so communication on that network is given time to
4212 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004213 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004214 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004215 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004216 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4217 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004218 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004219 if (DBG) log("Reaping " + nai.name());
4220 teardownUnneededNetwork(nai);
4221 }
4222 }
4223 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004224 }
4225
Paul Jensen2161a8e2014-09-11 11:00:39 -04004226 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4227 // being disconnected.
4228 // If only one Network's score or capabilities have been modified since the last time
4229 // this function was called, pass this Network in via the "changed" arugment, otherwise
4230 // pass null.
4231 // If only one Network has been changed but its NetworkCapabilities have not changed,
4232 // pass in the Network's score (from getCurrentScore()) prior to the change via
4233 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4234 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4235 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4236 // to avoid the slowness. It is not simply enough to process just "changed", for
4237 // example in the case where "changed"'s score decreases and another network should begin
4238 // satifying a NetworkRequest that "changed" currently satisfies.
4239
4240 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4241 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4242 // rematchNetworkAndRequests() handles.
4243 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004244 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4245 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004246 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004247 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4248 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4249 NascentState.NOT_JUST_VALIDATED,
4250 // Only reap the last time through the loop. Reaping before all rematching
4251 // is complete could incorrectly teardown a network that hasn't yet been
4252 // rematched.
4253 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4254 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004255 }
4256 }
4257 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004258
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004259 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004260 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004261 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004262 // For now only update icons for default connection.
4263 // TODO: Update WiFi and cellular icons separately. b/17237507
4264 if (!isDefaultNetwork(nai)) return;
4265
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004266 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004267 // Don't repeat publish.
4268 if (newInetCondition == mDefaultInetConditionPublished) return;
4269
4270 mDefaultInetConditionPublished = newInetCondition;
4271 sendInetConditionBroadcast(nai.networkInfo);
4272 }
4273
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004274 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4275 if (mLockdownTracker != null) {
4276 if (nai != null && nai.isVPN()) {
4277 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4278 } else {
4279 mLockdownTracker.onNetworkInfoChanged();
4280 }
4281 }
4282 }
4283
Robert Greenwalt7b816022014-04-18 15:25:25 -07004284 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4285 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004286 NetworkInfo oldInfo = null;
4287 synchronized (networkAgent) {
4288 oldInfo = networkAgent.networkInfo;
4289 networkAgent.networkInfo = newInfo;
4290 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004291 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004292
4293 if (oldInfo != null && oldInfo.getState() == state) {
4294 if (VDBG) log("ignoring duplicate network state non-change");
4295 return;
4296 }
4297 if (DBG) {
4298 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4299 (oldInfo == null ? "null" : oldInfo.getState()) +
4300 " to " + state);
4301 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004302
Paul Jenseneec75412014-08-04 12:21:19 -04004303 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004304 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004305 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004306 if (networkAgent.isVPN()) {
4307 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004308 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4309 (networkAgent.networkMisc == null ||
4310 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004311 } else {
4312 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4313 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004314 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004315 loge("Error creating network " + networkAgent.network.netId + ": "
4316 + e.getMessage());
4317 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004318 }
Paul Jenseneec75412014-08-04 12:21:19 -04004319 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004320 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004321 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004322 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04004323 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004324 if (networkAgent.isVPN()) {
4325 // Temporarily disable the default proxy (not global).
4326 synchronized (mProxyLock) {
4327 if (!mDefaultProxyDisabled) {
4328 mDefaultProxyDisabled = true;
4329 if (mGlobalProxy == null && mDefaultProxy != null) {
4330 sendProxyBroadcast(null);
4331 }
4332 }
4333 }
4334 // TODO: support proxy per network.
4335 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004336 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004337 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4338 ReapUnvalidatedNetworks.REAP);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004339 } else if (state == NetworkInfo.State.DISCONNECTED ||
4340 state == NetworkInfo.State.SUSPENDED) {
4341 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004342 if (networkAgent.isVPN()) {
4343 synchronized (mProxyLock) {
4344 if (mDefaultProxyDisabled) {
4345 mDefaultProxyDisabled = false;
4346 if (mGlobalProxy == null && mDefaultProxy != null) {
4347 sendProxyBroadcast(mDefaultProxy);
4348 }
4349 }
4350 }
4351 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004352 }
4353 }
4354
Robert Greenwaltac96c522014-06-03 16:43:57 -07004355 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4356 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004357 if (score < 0) {
4358 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4359 "). Bumping score to min of 0");
4360 score = 0;
4361 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004362
Paul Jensen2161a8e2014-09-11 11:00:39 -04004363 final int oldScore = nai.getCurrentScore();
4364 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004365
Paul Jensen57a767f2014-11-19 13:01:46 -05004366 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004367
Paul Jensenc8b9a742014-09-30 15:37:41 -04004368 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004369 }
4370
Robert Greenwalt9258c642014-03-26 16:47:06 -07004371 // notify only this one new request of the current state
4372 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4373 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4374 // TODO - read state from monitor to decide what to send.
4375// if (nai.networkMonitor.isLingering()) {
4376// notifyType = NetworkCallbacks.LOSING;
4377// } else if (nai.networkMonitor.isEvaluating()) {
4378// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4379// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004380 if (nri.mPendingIntent == null) {
4381 callCallbackForRequest(nri, nai, notifyType);
4382 } else {
4383 sendPendingIntentForRequest(nri, nai, notifyType);
4384 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004385 }
4386
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004387 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004388 // The NetworkInfo we actually send out has no bearing on the real
4389 // state of affairs. For example, if the default connection is mobile,
4390 // and a request for HIPRI has just gone away, we need to pretend that
4391 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4392 // the state to DISCONNECTED, even though the network is of type MOBILE
4393 // and is still connected.
4394 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4395 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004396 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004397 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004398 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004399 } else {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004400 info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004401 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4402 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4403 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4404 if (info.isFailover()) {
4405 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4406 nai.networkInfo.setFailover(false);
4407 }
4408 if (info.getReason() != null) {
4409 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4410 }
4411 if (info.getExtraInfo() != null) {
4412 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4413 }
4414 NetworkAgentInfo newDefaultAgent = null;
4415 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4416 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4417 if (newDefaultAgent != null) {
4418 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4419 newDefaultAgent.networkInfo);
4420 } else {
4421 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4422 }
4423 }
4424 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4425 mDefaultInetConditionPublished);
4426 final Intent immediateIntent = new Intent(intent);
4427 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
4428 sendStickyBroadcast(immediateIntent);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004429 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004430 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004431 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004432 }
4433 }
4434 }
4435
Robert Greenwalt7b816022014-04-18 15:25:25 -07004436 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004437 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004438 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004439 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4440 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4441 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004442 if (nri.mPendingIntent == null) {
4443 callCallbackForRequest(nri, networkAgent, notifyType);
4444 } else {
4445 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4446 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004447 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004448 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004449
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004450 private String notifyTypeToName(int notifyType) {
4451 switch (notifyType) {
4452 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4453 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4454 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4455 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4456 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4457 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4458 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4459 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4460 }
4461 return "UNKNOWN";
4462 }
4463
Jeff Sharkey69736342014-12-08 14:50:12 -08004464 /**
4465 * Notify other system services that set of active ifaces has changed.
4466 */
4467 private void notifyIfacesChanged() {
4468 try {
4469 mStatsService.forceUpdateIfaces();
4470 } catch (Exception ignored) {
4471 }
4472 }
4473
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004474 @Override
4475 public boolean addVpnAddress(String address, int prefixLength) {
4476 throwIfLockdownEnabled();
4477 int user = UserHandle.getUserId(Binder.getCallingUid());
4478 synchronized (mVpns) {
4479 return mVpns.get(user).addAddress(address, prefixLength);
4480 }
4481 }
4482
4483 @Override
4484 public boolean removeVpnAddress(String address, int prefixLength) {
4485 throwIfLockdownEnabled();
4486 int user = UserHandle.getUserId(Binder.getCallingUid());
4487 synchronized (mVpns) {
4488 return mVpns.get(user).removeAddress(address, prefixLength);
4489 }
4490 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004491
4492 @Override
4493 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4494 throwIfLockdownEnabled();
4495 int user = UserHandle.getUserId(Binder.getCallingUid());
4496 synchronized (mVpns) {
4497 return mVpns.get(user).setUnderlyingNetworks(networks);
4498 }
4499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500}