blob: d01816512f629edb3727997517b7c335f90ace80 [file] [log] [blame]
The Android Open Source Project28527d22009-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 Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baib5da5752012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070023import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
24import static android.net.ConnectivityManager.TYPE_DUMMY;
25import static android.net.ConnectivityManager.TYPE_ETHERNET;
26import static android.net.ConnectivityManager.TYPE_MOBILE;
27import static android.net.ConnectivityManager.TYPE_WIFI;
28import static android.net.ConnectivityManager.TYPE_WIMAX;
29import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070030import static android.net.ConnectivityManager.isNetworkTypeValid;
31import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070033
Vinit Deshapnde30ad2542013-08-21 13:09:01 -070034import android.app.AlarmManager;
Wink Saville32506bc2013-06-29 21:10:57 -070035import android.app.Notification;
36import android.app.NotificationManager;
37import android.app.PendingIntent;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080038import android.bluetooth.BluetoothTetheringDataTracker;
Wink Saville9a1a7ef2013-08-29 08:55:16 -070039import android.content.ActivityNotFoundException;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090043import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080044import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070045import android.content.IntentFilter;
The Android Open Source Project28527d22009-03-03 19:31:44 -080046import android.content.pm.PackageManager;
Robert Greenwalt39d56012013-07-16 12:06:09 -070047import android.content.res.Configuration;
tk.mun093f55c2011-10-13 22:51:57 +090048import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070049import android.database.ContentObserver;
Irfan Sheriff0ad0d132012-08-16 12:49:23 -070050import android.net.CaptivePortalTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080051import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080052import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080053import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070055import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070056import android.net.INetworkPolicyListener;
57import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070058import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070059import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080060import android.net.LinkProperties;
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -070061import android.net.LinkQualityInfo;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070062import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070064import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070066import android.net.NetworkInfo.DetailedState;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070067import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070068import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080069import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070070import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070071import android.net.Proxy;
72import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070073import android.net.RouteInfo;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -070074import android.net.SamplingDataTracker;
Jason Monka5bf2842013-07-03 17:04:33 -040075import android.net.Uri;
The Android Open Source Project28527d22009-03-03 19:31:44 -080076import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090077import android.net.wimax.WimaxManagerConstants;
Wink Saville32506bc2013-06-29 21:10:57 -070078import android.os.AsyncTask;
The Android Open Source Project28527d22009-03-03 19:31:44 -080079import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040080import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080081import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070082import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070083import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070084import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080085import android.os.Looper;
86import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070087import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070088import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070089import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -070090import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070091import android.os.RemoteException;
Wink Saville32506bc2013-06-29 21:10:57 -070092import android.os.ResultReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080093import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070094import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080095import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -070096import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080097import android.provider.Settings;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070098import android.security.Credentials;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -070099import android.security.KeyStore;
Wink Saville32506bc2013-06-29 21:10:57 -0700100import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700101import android.text.TextUtils;
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800102import android.util.Slog;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700103import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700104import android.util.SparseIntArray;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700105import android.util.Xml;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800106
Wink Saville32506bc2013-06-29 21:10:57 -0700107import com.android.internal.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400108import com.android.internal.annotations.GuardedBy;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700109import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700110import com.android.internal.net.VpnConfig;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700111import com.android.internal.net.VpnProfile;
Wink Saville32506bc2013-06-29 21:10:57 -0700112import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700113import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700114import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700115import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700116import com.android.internal.util.XmlUtils;
Jason Monka5bf2842013-07-03 17:04:33 -0400117import com.android.net.IProxyService;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700118import com.android.server.am.BatteryStatsService;
John Spurlock1f5cec72013-06-24 14:20:23 -0400119import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900120import com.android.server.connectivity.Nat464Xlat;
Jason Monka5bf2842013-07-03 17:04:33 -0400121import com.android.server.connectivity.PacManager;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800122import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700123import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700124import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700125import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700126import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700127import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700128
tk.mun093f55c2011-10-13 22:51:57 +0900129import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700130
Robert Greenwalt39d56012013-07-16 12:06:09 -0700131import org.xmlpull.v1.XmlPullParser;
132import org.xmlpull.v1.XmlPullParserException;
133
134import java.io.File;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800135import java.io.FileDescriptor;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700136import java.io.FileNotFoundException;
137import java.io.FileReader;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700138import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800139import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900140import java.lang.reflect.Constructor;
Wink Saville32506bc2013-06-29 21:10:57 -0700141import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700142import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700143import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700144import java.net.InetAddress;
Wink Saville32506bc2013-06-29 21:10:57 -0700145import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700146import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700147import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700148import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700149import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700150import java.util.GregorianCalendar;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700151import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700152import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700153import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700154import java.util.Map;
Wink Saville32506bc2013-06-29 21:10:57 -0700155import java.util.Random;
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700156import java.util.concurrent.atomic.AtomicBoolean;
Wink Saville32506bc2013-06-29 21:10:57 -0700157import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800158
159/**
160 * @hide
161 */
162public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700163 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800164
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700165 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700166 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800167
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700168 private static final boolean LOGD_RULES = false;
169
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700170 // TODO: create better separation between radio types and network types
171
Robert Greenwalt2034b912009-08-12 16:08:25 -0700172 // how long to wait before switching back to a radio's default network
173 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
174 // system property that can override the above value
175 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
176 "android.telephony.apn-restore";
177
Wink Saville32506bc2013-06-29 21:10:57 -0700178 // Default value if FAIL_FAST_TIME_MS is not set
179 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
180 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
181 private static final String FAIL_FAST_TIME_MS =
182 "persist.radio.fail_fast_time_ms";
183
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700184 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
185 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
186
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -0700187 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700188
189 private PendingIntent mSampleIntervalElapsedIntent;
190
191 // Set network sampling interval at 12 minutes, this way, even if the timers get
192 // aggregated, it will fire at around 15 minutes, which should allow us to
193 // aggregate this timer with other timers (specially the socket keep alive timers)
194 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
195
196 // start network sampling a minute after booting ...
197 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
198
199 AlarmManager mAlarmManager;
200
Robert Greenwaltbd492212011-05-06 17:10:53 -0700201 // used in recursive route setting to add gateways for the host for which
202 // a host route was requested.
203 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
204
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800205 private Tethering mTethering;
206
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700207 private KeyStore mKeyStore;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700208
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700209 @GuardedBy("mVpns")
210 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700211 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700212
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700213 private boolean mLockdownEnabled;
214 private LockdownVpnTracker mLockdownTracker;
215
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900216 private Nat464Xlat mClat;
217
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700218 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
219 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700220 /** Currently active network rules by UID. */
221 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700222 /** Set of ifaces that are costly. */
223 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700224
The Android Open Source Project28527d22009-03-03 19:31:44 -0800225 /**
226 * Sometimes we want to refer to the individual network state
227 * trackers separately, and sometimes we just want to treat them
228 * abstractly.
229 */
230 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700231
Irfan Sheriff0ad0d132012-08-16 12:49:23 -0700232 /* Handles captive portal check on a network */
233 private CaptivePortalTracker mCaptivePortalTracker;
234
Robert Greenwalt2034b912009-08-12 16:08:25 -0700235 /**
Wink Saville051a6642011-07-13 13:44:13 -0700236 * The link properties that define the current links
237 */
238 private LinkProperties mCurrentLinkProperties[];
239
240 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700241 * A per Net list of the PID's that requested access to the net
242 * used both as a refcount and for per-PID DNS selection
243 */
Mattias Falkd697aa22011-08-23 14:15:13 +0200244 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700245
Robert Greenwalt2034b912009-08-12 16:08:25 -0700246 // priority order of the nettrackers
247 // (excluding dynamically set mNetworkPreference)
248 // TODO - move mNetworkTypePreference into this
249 private int[] mPriorityList;
250
The Android Open Source Project28527d22009-03-03 19:31:44 -0800251 private Context mContext;
252 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700253 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700254 // 0 is full bad, 100 is full good
Wink Saville151eaa62013-01-31 00:30:13 +0000255 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700256 private int mDefaultInetConditionPublished = 0;
257 private boolean mInetConditionChangeInFlight = false;
258 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800259
Chia-chi Yehcc844502011-07-14 18:01:57 -0700260 private Object mDnsLock = new Object();
Robert Greenwalte41e3b32013-02-11 15:25:10 -0800261 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800262
263 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700264 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800265
Robert Greenwalt355205c2011-05-10 15:05:02 -0700266 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700267 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700268
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700269 private static final int ENABLED = 1;
270 private static final int DISABLED = 0;
271
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700272 private static final boolean ADD = true;
273 private static final boolean REMOVE = false;
274
275 private static final boolean TO_DEFAULT_TABLE = true;
276 private static final boolean TO_SECONDARY_TABLE = false;
277
Chad Brubaker49db4222013-07-15 16:34:04 -0700278 private static final boolean EXEMPT = true;
279 private static final boolean UNEXEMPT = false;
280
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700281 /**
282 * used internally as a delayed event to make us switch back to the
283 * default network
284 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700285 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700286
287 /**
288 * used internally to change our mobile data enabled flag
289 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700290 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700291
292 /**
293 * used internally to change our network preference setting
294 * arg1 = networkType to prefer
295 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700296 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700297
298 /**
299 * used internally to synchronize inet condition reports
300 * arg1 = networkType
301 * arg2 = condition (0 bad, 100 good)
302 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700303 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700304
305 /**
306 * used internally to mark the end of inet condition hold periods
307 * arg1 = networkType
308 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700309 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700310
311 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700312 * used internally to set enable/disable cellular data
313 * arg1 = ENBALED or DISABLED
314 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700315 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700316
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700317 /**
318 * used internally to clear a wakelock when transitioning
319 * from one net to another
320 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700321 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700322
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700323 /**
324 * used internally to reload global proxy settings
325 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700326 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700327
Robert Greenwalt34848c02011-03-25 13:09:25 -0700328 /**
329 * used internally to set external dependency met/unmet
330 * arg1 = ENABLED (met) or DISABLED (unmet)
331 * arg2 = NetworkType
332 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700333 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700334
Chia-chi Yehcc844502011-07-14 18:01:57 -0700335 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700336 * used internally to send a sticky broadcast delayed.
337 */
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700338 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700339
Jeff Sharkey805662d2011-08-19 02:24:24 -0700340 /**
341 * Used internally to
342 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
343 */
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700344 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700345
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700346 private static final int EVENT_VPN_STATE_CHANGED = 13;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700347
Wink Saville32506bc2013-06-29 21:10:57 -0700348 /**
349 * Used internally to disable fail fast of mobile data
350 */
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700351 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Saville32506bc2013-06-29 21:10:57 -0700352
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700353 /**
354 * user internally to indicate that data sampling interval is up
355 */
356 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
357
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700358 /** Handler used for internal events. */
359 private InternalHandler mHandler;
360 /** Handler used for incoming {@link NetworkStateTracker} events. */
361 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700362
363 // list of DeathRecipients used to make sure features are turned off when
364 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500365 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700366
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400367 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800368 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400369
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700370 private PowerManager.WakeLock mNetTransitionWakeLock;
371 private String mNetTransitionWakeLockCausedBy = "";
372 private int mNetTransitionWakeLockSerialNumber;
373 private int mNetTransitionWakeLockTimeout;
374
Robert Greenwalt94daa182010-09-01 11:34:05 -0700375 private InetAddress mDefaultDns;
376
Chad Brubaker49db4222013-07-15 16:34:04 -0700377 // Lock for protecting access to mAddedRoutes and mExemptAddresses
378 private final Object mRoutesLock = new Object();
379
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700380 // this collection is used to refcount the added routes - if there are none left
381 // it's time to remove the route from the route table
Chad Brubaker49db4222013-07-15 16:34:04 -0700382 @GuardedBy("mRoutesLock")
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700383 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
384
Chad Brubaker49db4222013-07-15 16:34:04 -0700385 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
386 // used to handle cleanup of exempt rules
387 @GuardedBy("mRoutesLock")
388 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
389
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700390 // used in DBG mode to track inet condition reports
391 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
392 private ArrayList mInetLog;
393
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700394 // track the current default http proxy - tell the world if we get a new one (real change)
395 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltf9661d32013-04-05 17:14:19 -0700396 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700397 private boolean mDefaultProxyDisabled = false;
398
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700399 // track the global proxy.
400 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700401
Jason Monka5bf2842013-07-03 17:04:33 -0400402 private PacManager mPacManager = null;
403
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700404 private SettingsObserver mSettingsObserver;
405
Robert Greenwalt34848c02011-03-25 13:09:25 -0700406 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700407 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700408
Robert Greenwalt12c44552009-12-07 11:33:18 -0800409 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700410 public int mSimultaneity;
411 public int mType;
412 public RadioAttributes(String init) {
413 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700414 mType = Integer.parseInt(fragments[0]);
415 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700416 }
417 }
418 RadioAttributes[] mRadioAttributes;
419
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700420 // the set of network types that can only be enabled by system/sig apps
421 List mProtectedNetworks;
422
John Spurlock1f5cec72013-06-24 14:20:23 -0400423 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700424
Wink Saville32506bc2013-06-29 21:10:57 -0700425 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
426
427 TelephonyManager mTelephonyManager;
John Spurlock1f5cec72013-06-24 14:20:23 -0400428
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700429 public ConnectivityService(Context context, INetworkManagementService netd,
430 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700431 // Currently, omitting a NetworkFactory will create one internally
432 // TODO: create here when we have cleaner WiMAX support
433 this(context, netd, statsService, policyManager, null);
434 }
435
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700436 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700437 INetworkStatsService statsService, INetworkPolicyManager policyManager,
438 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800439 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800440
Wink Saville775aad62010-09-02 19:23:52 -0700441 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
442 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700443 mHandler = new InternalHandler(handlerThread.getLooper());
444 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700445
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700446 if (netFactory == null) {
447 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
448 }
449
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800450 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800451 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
452 String id = Settings.Secure.getString(context.getContentResolver(),
453 Settings.Secure.ANDROID_ID);
454 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700455 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800456 SystemProperties.set("net.hostname", name);
457 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800458 }
459
Robert Greenwalt94daa182010-09-01 11:34:05 -0700460 // read our default dns server ip
Jeff Sharkey8c870452012-09-26 22:03:49 -0700461 String dns = Settings.Global.getString(context.getContentResolver(),
462 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700463 if (dns == null || dns.length() == 0) {
464 dns = context.getResources().getString(
465 com.android.internal.R.string.config_default_dns_server);
466 }
467 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800468 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
469 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800470 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700471 }
472
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700473 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700474 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700475 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700476 mKeyStore = KeyStore.getInstance();
Wink Saville32506bc2013-06-29 21:10:57 -0700477 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700478
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700479 try {
480 mPolicyManager.registerListener(mPolicyListener);
481 } catch (RemoteException e) {
482 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700483 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700484 }
485
486 final PowerManager powerManager = (PowerManager) context.getSystemService(
487 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700488 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
489 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
490 com.android.internal.R.integer.config_networkTransitionTimeout);
491
Robert Greenwalt2034b912009-08-12 16:08:25 -0700492 mNetTrackers = new NetworkStateTracker[
493 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700494 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700495
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700496 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700497 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700498
Robert Greenwalt2034b912009-08-12 16:08:25 -0700499 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700500 String[] raStrings = context.getResources().getStringArray(
501 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700502 for (String raString : raStrings) {
503 RadioAttributes r = new RadioAttributes(raString);
Wink Saville512c2202013-07-29 15:00:57 -0700504 if (VDBG) log("raString=" + raString + " r=" + r);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700505 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800506 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700507 continue;
508 }
509 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800510 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700511 r.mType);
512 continue;
513 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700514 mRadioAttributes[r.mType] = r;
515 }
516
Wink Saville00fe5092013-04-23 14:26:51 -0700517 // TODO: What is the "correct" way to do determine if this is a wifi only device?
518 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
519 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700520 String[] naStrings = context.getResources().getStringArray(
521 com.android.internal.R.array.networkAttributes);
522 for (String naString : naStrings) {
523 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700524 NetworkConfig n = new NetworkConfig(naString);
Wink Saville512c2202013-07-29 15:00:57 -0700525 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Savillef2a62832011-04-07 14:23:45 -0700526 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800527 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700528 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700529 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700530 }
Wink Saville00fe5092013-04-23 14:26:51 -0700531 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
532 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
533 n.type);
534 continue;
535 }
Wink Savillef2a62832011-04-07 14:23:45 -0700536 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800537 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700538 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700539 continue;
540 }
Wink Savillef2a62832011-04-07 14:23:45 -0700541 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800542 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700543 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700544 continue;
545 }
Wink Savillef2a62832011-04-07 14:23:45 -0700546 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700547 mNetworksDefined++;
548 } catch(Exception e) {
549 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700550 }
551 }
Wink Saville512c2202013-07-29 15:00:57 -0700552 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700553
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700554 mProtectedNetworks = new ArrayList<Integer>();
555 int[] protectedNetworks = context.getResources().getIntArray(
556 com.android.internal.R.array.config_protectedNetworks);
557 for (int p : protectedNetworks) {
558 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
559 mProtectedNetworks.add(p);
560 } else {
561 if (DBG) loge("Ignoring protectedNetwork " + p);
562 }
563 }
564
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700565 // high priority first
566 mPriorityList = new int[mNetworksDefined];
567 {
568 int insertionPoint = mNetworksDefined-1;
569 int currentLowest = 0;
570 int nextLowest = 0;
571 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700572 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700573 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700574 if (na.priority < currentLowest) continue;
575 if (na.priority > currentLowest) {
576 if (na.priority < nextLowest || nextLowest == 0) {
577 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700578 }
579 continue;
580 }
Wink Savillef2a62832011-04-07 14:23:45 -0700581 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700582 }
583 currentLowest = nextLowest;
584 nextLowest = 0;
585 }
586 }
587
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800588 // Update mNetworkPreference according to user mannually first then overlay config.xml
589 mNetworkPreference = getPersistedNetworkPreference();
590 if (mNetworkPreference == -1) {
591 for (int n : mPriorityList) {
592 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
593 mNetworkPreference = n;
594 break;
595 }
596 }
597 if (mNetworkPreference == -1) {
598 throw new IllegalStateException(
599 "You should set at least one default Network in config.xml!");
600 }
601 }
602
Mattias Falkd697aa22011-08-23 14:15:13 +0200603 mNetRequestersPids =
604 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700605 for (int i : mPriorityList) {
Mattias Falkd697aa22011-08-23 14:15:13 +0200606 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700607 }
608
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500609 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700610
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700611 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
612 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700613
614 // Create and start trackers for hard-coded networks
615 for (int targetNetworkType : mPriorityList) {
616 final NetworkConfig config = mNetConfigs[targetNetworkType];
617 final NetworkStateTracker tracker;
618 try {
619 tracker = netFactory.createTracker(targetNetworkType, config);
620 mNetTrackers[targetNetworkType] = tracker;
621 } catch (IllegalArgumentException e) {
622 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
623 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700624 continue;
625 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700626
627 tracker.startMonitoring(context, mTrackerHandler);
628 if (config.isDefault()) {
629 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800630 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700631 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800632
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700633 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800634
Robert Greenwaltf68291a2013-07-19 14:30:49 -0700635 //set up the listener for user state for creating user VPNs
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700636 IntentFilter intentFilter = new IntentFilter();
637 intentFilter.addAction(Intent.ACTION_USER_STARTING);
638 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
639 mContext.registerReceiverAsUser(
640 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900641 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
642
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700643 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700644 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700645 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900646 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700647 } catch (RemoteException e) {
648 loge("Error registering observer :" + e);
649 }
650
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700651 if (DBG) {
652 mInetLog = new ArrayList();
653 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700654
655 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
656 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800657
John Spurlock1f5cec72013-06-24 14:20:23 -0400658 mDataConnectionStats = new DataConnectionStats(mContext);
659 mDataConnectionStats.startMonitoring();
Jason Monka5bf2842013-07-03 17:04:33 -0400660
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700661 // start network sampling ..
662 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
663 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -0700664 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700665
666 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
667 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
668
669 IntentFilter filter = new IntentFilter();
670 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
671 mContext.registerReceiver(
672 new BroadcastReceiver() {
673 @Override
674 public void onReceive(Context context, Intent intent) {
675 String action = intent.getAction();
676 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
677 mHandler.sendMessage(mHandler.obtainMessage
678 (EVENT_SAMPLE_INTERVAL_ELAPSED));
679 }
680 }
681 },
682 new IntentFilter(filter));
683
Jason Monka5bf2842013-07-03 17:04:33 -0400684 mPacManager = new PacManager(mContext);
Wink Savillecb117d32013-08-29 14:57:08 -0700685
686 filter = new IntentFilter();
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700687 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
688 mContext.registerReceiver(mProvisioningReceiver, filter);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800689 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700690
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700691 /**
692 * Factory that creates {@link NetworkStateTracker} instances using given
693 * {@link NetworkConfig}.
694 */
695 public interface NetworkFactory {
696 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
697 }
698
699 private static class DefaultNetworkFactory implements NetworkFactory {
700 private final Context mContext;
701 private final Handler mTrackerHandler;
702
703 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
704 mContext = context;
705 mTrackerHandler = trackerHandler;
706 }
707
708 @Override
709 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
710 switch (config.radio) {
711 case TYPE_WIFI:
712 return new WifiStateTracker(targetNetworkType, config.name);
713 case TYPE_MOBILE:
714 return new MobileDataStateTracker(targetNetworkType, config.name);
715 case TYPE_DUMMY:
716 return new DummyDataStateTracker(targetNetworkType, config.name);
717 case TYPE_BLUETOOTH:
718 return BluetoothTetheringDataTracker.getInstance();
719 case TYPE_WIMAX:
720 return makeWimaxStateTracker(mContext, mTrackerHandler);
721 case TYPE_ETHERNET:
722 return EthernetDataTracker.getInstance();
723 default:
724 throw new IllegalArgumentException(
725 "Trying to create a NetworkStateTracker for an unknown radio type: "
726 + config.radio);
727 }
728 }
729 }
730
731 /**
732 * Loads external WiMAX library and registers as system service, returning a
733 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
734 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
735 */
736 private static NetworkStateTracker makeWimaxStateTracker(
737 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700738 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900739 DexClassLoader wimaxClassLoader;
740 Class wimaxStateTrackerClass = null;
741 Class wimaxServiceClass = null;
742 Class wimaxManagerClass;
743 String wimaxJarLocation;
744 String wimaxLibLocation;
745 String wimaxManagerClassName;
746 String wimaxServiceClassName;
747 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800748
tk.mun093f55c2011-10-13 22:51:57 +0900749 NetworkStateTracker wimaxStateTracker = null;
750
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700751 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900752 com.android.internal.R.bool.config_wimaxEnabled);
753
754 if (isWimaxEnabled) {
755 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700756 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900757 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700758 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900759 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700760 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900761 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700762 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900763 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700764 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900765 com.android.internal.R.string.config_wimaxStateTrackerClassname);
766
Dianne Hackborndc456a62012-11-08 11:12:09 -0800767 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900768 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700769 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900770 wimaxLibLocation, ClassLoader.getSystemClassLoader());
771
772 try {
773 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
774 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
775 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
776 } catch (ClassNotFoundException ex) {
777 loge("Exception finding Wimax classes: " + ex.toString());
778 return null;
779 }
780 } catch(Resources.NotFoundException ex) {
781 loge("Wimax Resources does not exist!!! ");
782 return null;
783 }
784
785 try {
Dianne Hackborndc456a62012-11-08 11:12:09 -0800786 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900787
788 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
789 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700790 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
791 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900792
793 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
794 (new Class[] {Context.class, wimaxStateTrackerClass});
795 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700796 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900797 wmxSrvConst.setAccessible(false);
798
799 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
800
801 } catch(Exception ex) {
802 loge("Exception creating Wimax classes: " + ex.toString());
803 return null;
804 }
805 } else {
806 loge("Wimax is not enabled or not added to the network attributes!!! ");
807 return null;
808 }
809
810 return wimaxStateTracker;
811 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700812
The Android Open Source Project28527d22009-03-03 19:31:44 -0800813 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700814 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800815 * @param preference the new preference
816 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700817 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800818 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700819
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700820 mHandler.sendMessage(
821 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800822 }
823
824 public int getNetworkPreference() {
825 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700826 int preference;
827 synchronized(this) {
828 preference = mNetworkPreference;
829 }
830 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800831 }
832
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700833 private void handleSetNetworkPreference(int preference) {
834 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700835 mNetConfigs[preference] != null &&
836 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700837 if (mNetworkPreference != preference) {
838 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownc67cf562012-09-25 15:03:20 -0700839 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700840 synchronized(this) {
841 mNetworkPreference = preference;
842 }
843 enforcePreference();
844 }
845 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800846 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700847
Wink Saville4f0de1e2011-08-04 15:01:58 -0700848 private int getConnectivityChangeDelay() {
849 final ContentResolver cr = mContext.getContentResolver();
850
851 /** Check system properties for the default value then use secure settings value, if any. */
852 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey8c870452012-09-26 22:03:49 -0700853 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
854 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
855 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700856 defaultDelay);
857 }
858
The Android Open Source Project28527d22009-03-03 19:31:44 -0800859 private int getPersistedNetworkPreference() {
860 final ContentResolver cr = mContext.getContentResolver();
861
Jeff Brownc67cf562012-09-25 15:03:20 -0700862 final int networkPrefSetting = Settings.Global
863 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800864
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800865 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800866 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700867
The Android Open Source Project28527d22009-03-03 19:31:44 -0800868 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700869 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800870 * In this method, we only tear down a non-preferred network. Establishing
871 * a connection to the preferred network is taken care of when we handle
872 * the disconnect event from the non-preferred network
873 * (see {@link #handleDisconnect(NetworkInfo)}).
874 */
875 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700876 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800877 return;
878
Robert Greenwalt2034b912009-08-12 16:08:25 -0700879 if (!mNetTrackers[mNetworkPreference].isAvailable())
880 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800881
Robert Greenwalt2034b912009-08-12 16:08:25 -0700882 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700883 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700884 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700885 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800886 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700887 " in enforcePreference");
888 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700889 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800890 }
891 }
892 }
893
894 private boolean teardown(NetworkStateTracker netTracker) {
895 if (netTracker.teardown()) {
896 netTracker.setTeardownRequested(true);
897 return true;
898 } else {
899 return false;
900 }
901 }
902
903 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700904 * Check if UID should be blocked from using the network represented by the
905 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700906 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700907 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
908 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700909
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700910 final boolean networkCostly;
911 final int uidRules;
912 synchronized (mRulesLock) {
913 networkCostly = mMeteredIfaces.contains(iface);
914 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700915 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700916
917 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
918 return true;
919 }
920
921 // no restrictive rules; network is visible
922 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700923 }
924
925 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700926 * Return a filtered {@link NetworkInfo}, potentially marked
927 * {@link DetailedState#BLOCKED} based on
928 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700929 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700930 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
931 NetworkInfo info = tracker.getNetworkInfo();
932 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700933 // network is blocked; clone and override state
934 info = new NetworkInfo(info);
935 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700936 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700937 if (mLockdownTracker != null) {
938 info = mLockdownTracker.augmentNetworkInfo(info);
939 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700940 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700941 }
942
943 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800944 * Return NetworkInfo for the active (i.e., connected) network interface.
945 * It is assumed that at most one network is active at a time. If more
946 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700947 * @return the info for the active network, or {@code null} if none is
948 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800949 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700950 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800951 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700952 enforceAccessPermission();
953 final int uid = Binder.getCallingUid();
954 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800955 }
956
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700957 /**
958 * Find the first Provisioning network.
959 *
960 * @return NetworkInfo or null if none.
961 */
962 private NetworkInfo getProvisioningNetworkInfo() {
963 enforceAccessPermission();
964
965 // Find the first Provisioning Network
966 NetworkInfo provNi = null;
967 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Savilleb1a32022013-09-05 12:02:25 -0700968 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700969 provNi = ni;
970 break;
971 }
972 }
973 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
974 return provNi;
975 }
976
977 /**
978 * Find the first Provisioning network or the ActiveDefaultNetwork
979 * if there is no Provisioning network
980 *
981 * @return NetworkInfo or null if none.
982 */
983 @Override
984 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
985 enforceAccessPermission();
986
987 NetworkInfo provNi = getProvisioningNetworkInfo();
988 if (provNi == null) {
989 final int uid = Binder.getCallingUid();
990 provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
991 }
992 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
993 return provNi;
994 }
995
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700996 public NetworkInfo getActiveNetworkInfoUnfiltered() {
997 enforceAccessPermission();
998 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
999 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
1000 if (tracker != null) {
1001 return tracker.getNetworkInfo();
1002 }
1003 }
1004 return null;
1005 }
1006
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001007 @Override
1008 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1009 enforceConnectivityInternalPermission();
1010 return getNetworkInfo(mActiveDefaultNetwork, uid);
1011 }
1012
1013 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001014 public NetworkInfo getNetworkInfo(int networkType) {
1015 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001016 final int uid = Binder.getCallingUid();
1017 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001018 }
1019
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001020 private NetworkInfo getNetworkInfo(int networkType, int uid) {
1021 NetworkInfo info = null;
1022 if (isNetworkTypeValid(networkType)) {
1023 final NetworkStateTracker tracker = mNetTrackers[networkType];
1024 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001025 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001026 }
1027 }
1028 return info;
1029 }
1030
1031 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001032 public NetworkInfo[] getAllNetworkInfo() {
1033 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001034 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -07001035 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001036 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001037 for (NetworkStateTracker tracker : mNetTrackers) {
1038 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001039 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001040 }
1041 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001042 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001043 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001044 }
1045
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001046 @Override
1047 public boolean isNetworkSupported(int networkType) {
1048 enforceAccessPermission();
1049 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
1050 }
1051
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001052 /**
1053 * Return LinkProperties for the active (i.e., connected) default
1054 * network interface. It is assumed that at most one default network
1055 * is active at a time. If more than one is active, it is indeterminate
1056 * which will be returned.
1057 * @return the ip properties for the active network, or {@code null} if
1058 * none is active
1059 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001060 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001061 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -07001062 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001063 }
1064
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001065 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001066 public LinkProperties getLinkProperties(int networkType) {
1067 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001068 if (isNetworkTypeValid(networkType)) {
1069 final NetworkStateTracker tracker = mNetTrackers[networkType];
1070 if (tracker != null) {
1071 return tracker.getLinkProperties();
1072 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001073 }
1074 return null;
1075 }
1076
Jeff Sharkey21062e72011-05-28 20:56:34 -07001077 @Override
1078 public NetworkState[] getAllNetworkState() {
1079 enforceAccessPermission();
1080 final int uid = Binder.getCallingUid();
1081 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001082 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -07001083 for (NetworkStateTracker tracker : mNetTrackers) {
1084 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001085 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -07001086 result.add(new NetworkState(
1087 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1088 }
1089 }
1090 }
1091 return result.toArray(new NetworkState[result.size()]);
1092 }
1093
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001094 private NetworkState getNetworkStateUnchecked(int networkType) {
1095 if (isNetworkTypeValid(networkType)) {
1096 final NetworkStateTracker tracker = mNetTrackers[networkType];
1097 if (tracker != null) {
1098 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1099 tracker.getLinkCapabilities());
1100 }
1101 }
1102 return null;
1103 }
1104
1105 @Override
1106 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1107 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001108
1109 final long token = Binder.clearCallingIdentity();
1110 try {
1111 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1112 if (state != null) {
1113 try {
1114 return mPolicyManager.getNetworkQuotaInfo(state);
1115 } catch (RemoteException e) {
1116 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001117 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001118 return null;
1119 } finally {
1120 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001121 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001122 }
1123
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001124 @Override
1125 public boolean isActiveNetworkMetered() {
1126 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001127 final long token = Binder.clearCallingIdentity();
1128 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001129 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001130 } finally {
1131 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001132 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001133 }
1134
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001135 private boolean isNetworkMeteredUnchecked(int networkType) {
1136 final NetworkState state = getNetworkStateUnchecked(networkType);
1137 if (state != null) {
1138 try {
1139 return mPolicyManager.isNetworkMetered(state);
1140 } catch (RemoteException e) {
1141 }
1142 }
1143 return false;
1144 }
1145
The Android Open Source Project28527d22009-03-03 19:31:44 -08001146 public boolean setRadios(boolean turnOn) {
1147 boolean result = true;
1148 enforceChangePermission();
1149 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001150 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001151 }
1152 return result;
1153 }
1154
1155 public boolean setRadio(int netType, boolean turnOn) {
1156 enforceChangePermission();
1157 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1158 return false;
1159 }
1160 NetworkStateTracker tracker = mNetTrackers[netType];
1161 return tracker != null && tracker.setRadio(turnOn);
1162 }
1163
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001164 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1165 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001166 public void interfaceClassDataActivityChanged(String label, boolean active) {
1167 int deviceType = Integer.parseInt(label);
1168 sendDataActivityBroadcast(deviceType, active);
1169 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001170 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001171
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001172 /**
1173 * Used to notice when the calling process dies so we can self-expire
1174 *
1175 * Also used to know if the process has cleaned up after itself when
1176 * our auto-expire timer goes off. The timer has a link to an object.
1177 *
1178 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001179 private class FeatureUser implements IBinder.DeathRecipient {
1180 int mNetworkType;
1181 String mFeature;
1182 IBinder mBinder;
1183 int mPid;
1184 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001185 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001186
1187 FeatureUser(int type, String feature, IBinder binder) {
1188 super();
1189 mNetworkType = type;
1190 mFeature = feature;
1191 mBinder = binder;
1192 mPid = getCallingPid();
1193 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001194 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001195
Robert Greenwalt2034b912009-08-12 16:08:25 -07001196 try {
1197 mBinder.linkToDeath(this, 0);
1198 } catch (RemoteException e) {
1199 binderDied();
1200 }
1201 }
1202
1203 void unlinkDeathRecipient() {
1204 mBinder.unlinkToDeath(this, 0);
1205 }
1206
1207 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001208 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001209 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1210 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001211 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001212 }
1213
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001214 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001215 if (VDBG) {
1216 log("ConnectivityService FeatureUser expire(" +
1217 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1218 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1219 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001220 stopUsingNetworkFeature(this, false);
1221 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001222
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001223 public boolean isSameUser(FeatureUser u) {
1224 if (u == null) return false;
1225
1226 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1227 }
1228
1229 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1230 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1231 TextUtils.equals(mFeature, feature)) {
1232 return true;
1233 }
1234 return false;
1235 }
1236
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001237 public String toString() {
1238 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1239 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1240 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001241 }
1242
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001243 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001244 public int startUsingNetworkFeature(int networkType, String feature,
1245 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001246 long startTime = 0;
1247 if (DBG) {
1248 startTime = SystemClock.elapsedRealtime();
1249 }
Wink Savillea7d56572011-09-21 11:05:43 -07001250 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001251 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1252 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001253 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001254 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001255 try {
1256 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1257 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001258 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001259 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001260
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001261 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001262
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001263 // TODO - move this into individual networktrackers
1264 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001265
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001266 if (mLockdownEnabled) {
1267 // Since carrier APNs usually aren't available from VPN
1268 // endpoint, mark them as unavailable.
1269 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1270 }
1271
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001272 if (mProtectedNetworks.contains(usedNetworkType)) {
1273 enforceConnectivityInternalPermission();
1274 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001275
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001276 // if UID is restricted, don't allow them to bring up metered APNs
1277 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1278 final int uidRules;
1279 synchronized (mRulesLock) {
1280 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1281 }
1282 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001283 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001284 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001285
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001286 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1287 if (network != null) {
1288 Integer currentPid = new Integer(getCallingPid());
1289 if (usedNetworkType != networkType) {
1290 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001291
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001292 if (ni.isAvailable() == false) {
1293 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1294 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001295 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001296 } else {
1297 // else make the attempt anyway - probably giving REQUEST_STARTED below
1298 if (DBG) {
1299 log("special network not available, but try anyway ni=" +
1300 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001301 }
1302 }
1303 }
1304
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001305 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001306
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001307 synchronized(this) {
1308 boolean addToList = true;
1309 if (restoreTimer < 0) {
1310 // In case there is no timer is specified for the feature,
1311 // make sure we don't add duplicate entry with the same request.
1312 for (FeatureUser u : mFeatureUsers) {
1313 if (u.isSameUser(f)) {
1314 // Duplicate user is found. Do not add.
1315 addToList = false;
1316 break;
1317 }
1318 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001319 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001320
1321 if (addToList) mFeatureUsers.add(f);
1322 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1323 // this gets used for per-pid dns when connected
1324 mNetRequestersPids[usedNetworkType].add(currentPid);
1325 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001326 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001327
1328 if (restoreTimer >= 0) {
1329 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1330 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1331 }
1332
1333 if ((ni.isConnectedOrConnecting() == true) &&
1334 !network.isTeardownRequested()) {
1335 if (ni.isConnected() == true) {
1336 final long token = Binder.clearCallingIdentity();
1337 try {
1338 // add the pid-specific dns
1339 handleDnsConfigurationChange(usedNetworkType);
1340 if (VDBG) log("special network already active");
1341 } finally {
1342 Binder.restoreCallingIdentity(token);
1343 }
Wink Saville64e3f782012-07-10 12:37:54 -07001344 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001345 }
1346 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001347 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001348 }
1349
1350 // check if the radio in play can make another contact
1351 // assume if cannot for now
1352
1353 if (DBG) {
1354 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1355 feature);
1356 }
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001357 if (network.reconnect()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001358 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001359 return PhoneConstants.APN_REQUEST_STARTED;
1360 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001361 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001362 return PhoneConstants.APN_REQUEST_FAILED;
1363 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001364 } else {
1365 // need to remember this unsupported request so we respond appropriately on stop
1366 synchronized(this) {
1367 mFeatureUsers.add(f);
1368 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1369 // this gets used for per-pid dns when connected
1370 mNetRequestersPids[usedNetworkType].add(currentPid);
1371 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001372 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001373 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001374 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001375 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001376 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001377 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
Wink Saville64e3f782012-07-10 12:37:54 -07001378 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001379 } finally {
1380 if (DBG) {
1381 final long execTime = SystemClock.elapsedRealtime() - startTime;
1382 if (execTime > 250) {
1383 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1384 } else {
1385 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1386 }
1387 }
1388 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001389 }
1390
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001391 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001392 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001393 enforceChangePermission();
1394
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001395 int pid = getCallingPid();
1396 int uid = getCallingUid();
1397
1398 FeatureUser u = null;
1399 boolean found = false;
1400
1401 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001402 for (FeatureUser x : mFeatureUsers) {
1403 if (x.isSameUser(pid, uid, networkType, feature)) {
1404 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001405 found = true;
1406 break;
1407 }
1408 }
1409 }
1410 if (found && u != null) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001411 if (VDBG) log("stopUsingNetworkFeature: X");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001412 // stop regardless of how many other time this proc had called start
1413 return stopUsingNetworkFeature(u, true);
1414 } else {
1415 // none found!
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001416 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001417 return 1;
1418 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001419 }
1420
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001421 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1422 int networkType = u.mNetworkType;
1423 String feature = u.mFeature;
1424 int pid = u.mPid;
1425 int uid = u.mUid;
1426
1427 NetworkStateTracker tracker = null;
1428 boolean callTeardown = false; // used to carry our decision outside of sync block
1429
Wink Savillea7d56572011-09-21 11:05:43 -07001430 if (VDBG) {
1431 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001432 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001433
The Android Open Source Project28527d22009-03-03 19:31:44 -08001434 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001435 if (DBG) {
1436 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1437 ", net is invalid");
1438 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001439 return -1;
1440 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001441
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001442 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1443 // sync block
1444 synchronized(this) {
1445 // check if this process still has an outstanding start request
1446 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001447 if (VDBG) {
1448 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1449 ", ignoring");
1450 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001451 return 1;
1452 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001453 u.unlinkDeathRecipient();
1454 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1455 // If we care about duplicate requests, check for that here.
1456 //
1457 // This is done to support the extension of a request - the app
1458 // can request we start the network feature again and renew the
1459 // auto-shutoff delay. Normal "stop" calls from the app though
1460 // do not pay attention to duplicate requests - in effect the
1461 // API does not refcount and a single stop will counter multiple starts.
1462 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001463 for (FeatureUser x : mFeatureUsers) {
1464 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001465 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001466 return 1;
1467 }
1468 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001469 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001470
repo syncf5de5572011-07-29 23:55:49 -07001471 // TODO - move to individual network trackers
1472 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1473
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001474 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001475 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001476 if (DBG) {
1477 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1478 " no known tracker for used net type " + usedNetworkType);
1479 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001480 return -1;
1481 }
1482 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001483 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001484 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalte767d812013-02-12 17:18:25 -08001485
1486 final long token = Binder.clearCallingIdentity();
1487 try {
1488 reassessPidDns(pid, true);
1489 } finally {
1490 Binder.restoreCallingIdentity(token);
1491 }
Mattias Falkd697aa22011-08-23 14:15:13 +02001492 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001493 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001494 if (VDBG) {
1495 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1496 " others still using it");
1497 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001498 return 1;
1499 }
1500 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001501 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001502 if (DBG) {
1503 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1504 " not a known feature - dropping");
1505 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001506 }
1507 }
Wink Savillea7d56572011-09-21 11:05:43 -07001508
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001509 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001510 if (DBG) {
1511 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1512 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001513 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001514 return 1;
1515 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001516 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001517 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001518 }
1519
1520 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001521 * @deprecated use requestRouteToHostAddress instead
1522 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001523 * Ensure that a network route exists to deliver traffic to the specified
1524 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001525 * @param networkType the type of the network over which traffic to the
1526 * specified host is to be routed
1527 * @param hostAddress the IP address of the host to which the route is
1528 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001529 * @return {@code true} on success, {@code false} on failure
1530 */
1531 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001532 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1533
1534 if (inetAddress == null) {
1535 return false;
1536 }
1537
1538 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1539 }
1540
1541 /**
1542 * Ensure that a network route exists to deliver traffic to the specified
1543 * host via the specified network interface.
1544 * @param networkType the type of the network over which traffic to the
1545 * specified host is to be routed
1546 * @param hostAddress the IP address of the host to which the route is
1547 * desired
1548 * @return {@code true} on success, {@code false} on failure
1549 */
1550 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001551 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001552 if (mProtectedNetworks.contains(networkType)) {
1553 enforceConnectivityInternalPermission();
1554 }
1555
The Android Open Source Project28527d22009-03-03 19:31:44 -08001556 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001557 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001558 return false;
1559 }
1560 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001561 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001562
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001563 if (tracker == null || (netState != DetailedState.CONNECTED &&
1564 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001565 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001566 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07001567 log("requestRouteToHostAddress on down network "
1568 + "(" + networkType + ") - dropped"
1569 + " tracker=" + tracker
1570 + " netState=" + netState
1571 + " isTeardownRequested="
1572 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001573 }
1574 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001575 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001576 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001577 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001578 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001579 LinkProperties lp = tracker.getLinkProperties();
Chad Brubaker49db4222013-07-15 16:34:04 -07001580 boolean ok = addRouteToAddress(lp, addr, EXEMPT);
Wink Saville32506bc2013-06-29 21:10:57 -07001581 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1582 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001583 } catch (UnknownHostException e) {
1584 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1585 } finally {
1586 Binder.restoreCallingIdentity(token);
1587 }
Wink Saville32506bc2013-06-29 21:10:57 -07001588 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001589 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001590 }
1591
Chad Brubaker49db4222013-07-15 16:34:04 -07001592 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1593 boolean exempt) {
1594 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001595 }
1596
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001597 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001598 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001599 }
1600
Chad Brubaker49db4222013-07-15 16:34:04 -07001601 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1602 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001603 }
1604
1605 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001606 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
Robert Greenwalt98107422011-07-22 11:55:33 -07001607 }
1608
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001609 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
Chad Brubaker49db4222013-07-15 16:34:04 -07001610 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001611 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001612 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001613 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001614 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001615 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001616 if (bestRoute.getGateway().equals(addr)) {
1617 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001618 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001619 } else {
1620 // if we will connect to this through another route, add a direct route
1621 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001622 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001623 }
1624 }
Chad Brubaker49db4222013-07-15 16:34:04 -07001625 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001626 }
1627
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001628 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
Chad Brubaker49db4222013-07-15 16:34:04 -07001629 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001630 if ((lp == null) || (r == null)) {
1631 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001632 return false;
1633 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001634
1635 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001636 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001637 return false;
1638 }
1639
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001640 String ifaceName = r.getInterface();
1641 if(ifaceName == null) {
1642 loge("Error modifying route - no interface name");
1643 return false;
1644 }
Robert Greenwalt59070cf2013-04-11 13:48:16 -07001645 if (r.hasGateway()) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001646 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001647 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001648 if (bestRoute.getGateway().equals(r.getGateway())) {
1649 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001650 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001651 } else {
1652 // if we will connect to our gateway through another route, add a direct
1653 // route to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001654 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1655 bestRoute.getGateway(),
1656 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001657 }
Chad Brubaker49db4222013-07-15 16:34:04 -07001658 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001659 }
1660 }
1661 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001662 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001663 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001664 if (toDefaultTable) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001665 synchronized (mRoutesLock) {
1666 // only track default table - only one apps can effect
1667 mAddedRoutes.add(r);
1668 mNetd.addRoute(ifaceName, r);
1669 if (exempt) {
1670 LinkAddress dest = r.getDestination();
1671 if (!mExemptAddresses.contains(dest)) {
1672 mNetd.setHostExemption(dest);
1673 mExemptAddresses.add(dest);
1674 }
1675 }
1676 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001677 } else {
1678 mNetd.addSecondaryRoute(ifaceName, r);
1679 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001680 } catch (Exception e) {
1681 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001682 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001683 return false;
1684 }
1685 } else {
1686 // if we remove this one and there are no more like it, then refcount==0 and
1687 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001688 if (toDefaultTable) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001689 synchronized (mRoutesLock) {
1690 mAddedRoutes.remove(r);
1691 if (mAddedRoutes.contains(r) == false) {
1692 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1693 try {
1694 mNetd.removeRoute(ifaceName, r);
1695 LinkAddress dest = r.getDestination();
1696 if (mExemptAddresses.contains(dest)) {
1697 mNetd.clearHostExemption(dest);
1698 mExemptAddresses.remove(dest);
1699 }
1700 } catch (Exception e) {
1701 // never crash - catch them all
1702 if (VDBG) loge("Exception trying to remove a route: " + e);
1703 return false;
1704 }
1705 } else {
1706 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001707 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001708 }
1709 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001710 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001711 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001712 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001713 } catch (Exception e) {
1714 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001715 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001716 return false;
1717 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001718 }
1719 }
1720 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001721 }
1722
1723 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001724 * @see ConnectivityManager#getMobileDataEnabled()
1725 */
1726 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001727 // TODO: This detail should probably be in DataConnectionTracker's
1728 // which is where we store the value and maybe make this
1729 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001730 enforceAccessPermission();
Jeff Sharkey8b361572012-09-26 15:54:06 -07001731 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1732 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001733 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001734 return retVal;
1735 }
1736
Robert Greenwalt34848c02011-03-25 13:09:25 -07001737 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001738 enforceConnectivityInternalPermission();
1739
Robert Greenwalt34848c02011-03-25 13:09:25 -07001740 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1741 (met ? ENABLED : DISABLED), networkType));
1742 }
1743
1744 private void handleSetDependencyMet(int networkType, boolean met) {
1745 if (mNetTrackers[networkType] != null) {
1746 if (DBG) {
1747 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1748 }
1749 mNetTrackers[networkType].setDependencyMet(met);
1750 }
1751 }
1752
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001753 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1754 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001755 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001756 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001757 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001758 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001759 }
1760
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001761 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001762 // skip update when we've already applied rules
1763 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1764 if (oldRules == uidRules) return;
1765
1766 mUidRules.put(uid, uidRules);
1767 }
1768
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001769 // TODO: notify UID when it has requested targeted updates
1770 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001771
1772 @Override
1773 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001774 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001775 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001776 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001777 }
1778
1779 synchronized (mRulesLock) {
1780 mMeteredIfaces.clear();
1781 for (String iface : meteredIfaces) {
1782 mMeteredIfaces.add(iface);
1783 }
1784 }
1785 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001786
1787 @Override
1788 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1789 // caller is NPMS, since we only register with them
1790 if (LOGD_RULES) {
1791 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1792 }
1793
1794 // kick off connectivity change broadcast for active network, since
1795 // global background policy change is radical.
1796 final int networkType = mActiveDefaultNetwork;
1797 if (isNetworkTypeValid(networkType)) {
1798 final NetworkStateTracker tracker = mNetTrackers[networkType];
1799 if (tracker != null) {
1800 final NetworkInfo info = tracker.getNetworkInfo();
1801 if (info != null && info.isConnected()) {
1802 sendConnectedBroadcast(info);
1803 }
1804 }
1805 }
1806 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001807 };
1808
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001809 /**
1810 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1811 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001812 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001813 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001814 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001815
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001816 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001817 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001818 }
1819
1820 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001821 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001822 if (VDBG) {
1823 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001824 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001825 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1826 }
tk.mun5eee1042012-01-06 10:43:52 +09001827 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1828 if (VDBG) {
1829 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1830 }
1831 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1832 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001833 }
1834
1835 @Override
1836 public void setPolicyDataEnable(int networkType, boolean enabled) {
1837 // only someone like NPMS should only be calling us
1838 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1839
1840 mHandler.sendMessage(mHandler.obtainMessage(
1841 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1842 }
1843
1844 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1845 if (isNetworkTypeValid(networkType)) {
1846 final NetworkStateTracker tracker = mNetTrackers[networkType];
1847 if (tracker != null) {
1848 tracker.setPolicyDataEnable(enabled);
1849 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001850 }
1851 }
1852
The Android Open Source Project28527d22009-03-03 19:31:44 -08001853 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001854 mContext.enforceCallingOrSelfPermission(
1855 android.Manifest.permission.ACCESS_NETWORK_STATE,
1856 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001857 }
1858
1859 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001860 mContext.enforceCallingOrSelfPermission(
1861 android.Manifest.permission.CHANGE_NETWORK_STATE,
1862 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001863 }
1864
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001865 // TODO Make this a special check when it goes public
1866 private void enforceTetherChangePermission() {
1867 mContext.enforceCallingOrSelfPermission(
1868 android.Manifest.permission.CHANGE_NETWORK_STATE,
1869 "ConnectivityService");
1870 }
1871
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001872 private void enforceTetherAccessPermission() {
1873 mContext.enforceCallingOrSelfPermission(
1874 android.Manifest.permission.ACCESS_NETWORK_STATE,
1875 "ConnectivityService");
1876 }
1877
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001878 private void enforceConnectivityInternalPermission() {
1879 mContext.enforceCallingOrSelfPermission(
1880 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1881 "ConnectivityService");
1882 }
1883
Chad Brubaker11f22252013-07-11 13:29:30 -07001884 private void enforceMarkNetworkSocketPermission() {
1885 //Media server special case
1886 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1887 return;
1888 }
1889 mContext.enforceCallingOrSelfPermission(
1890 android.Manifest.permission.MARK_NETWORK_SOCKET,
1891 "ConnectivityService");
1892 }
1893
The Android Open Source Project28527d22009-03-03 19:31:44 -08001894 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001895 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1896 * network, we ignore it. If it is for the active network, we send out a
1897 * broadcast. But first, we check whether it might be possible to connect
1898 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001899 * @param info the {@code NetworkInfo} for the network
1900 */
1901 private void handleDisconnect(NetworkInfo info) {
1902
Robert Greenwalt2034b912009-08-12 16:08:25 -07001903 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001904
Robert Greenwalt2034b912009-08-12 16:08:25 -07001905 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Baie2462442012-06-28 15:26:19 -07001906
1907 // Remove idletimer previously setup in {@code handleConnect}
1908 removeDataActivityTracking(prevNetType);
1909
The Android Open Source Project28527d22009-03-03 19:31:44 -08001910 /*
1911 * If the disconnected network is not the active one, then don't report
1912 * this as a loss of connectivity. What probably happened is that we're
1913 * getting the disconnect for a network that we explicitly disabled
1914 * in accordance with network preference policies.
1915 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001916 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkd697aa22011-08-23 14:15:13 +02001917 List<Integer> pids = mNetRequestersPids[prevNetType];
1918 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001919 // will remove them because the net's no longer connected
1920 // need to do this now as only now do we know the pids and
1921 // can properly null things that are no longer referenced.
1922 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001923 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001924 }
1925
The Android Open Source Project28527d22009-03-03 19:31:44 -08001926 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001927 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001928 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001929 if (info.isFailover()) {
1930 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1931 info.setFailover(false);
1932 }
1933 if (info.getReason() != null) {
1934 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1935 }
1936 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001937 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1938 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001939 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001940
Robert Greenwalt34848c02011-03-25 13:09:25 -07001941 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001942 tryFailover(prevNetType);
1943 if (mActiveDefaultNetwork != -1) {
1944 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001945 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1946 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001947 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001948 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1949 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001950 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001951 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001952
1953 // Reset interface if no other connections are using the same interface
1954 boolean doReset = true;
1955 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1956 if (linkProperties != null) {
1957 String oldIface = linkProperties.getInterfaceName();
1958 if (TextUtils.isEmpty(oldIface) == false) {
1959 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1960 if (networkStateTracker == null) continue;
1961 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1962 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1963 LinkProperties l = networkStateTracker.getLinkProperties();
1964 if (l == null) continue;
1965 if (oldIface.equals(l.getInterfaceName())) {
1966 doReset = false;
1967 break;
1968 }
1969 }
1970 }
1971 }
1972 }
1973
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001974 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001975 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001976
Jeff Sharkey971cd162011-08-29 16:02:57 -07001977 final Intent immediateIntent = new Intent(intent);
1978 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1979 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001980 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001981 /*
1982 * If the failover network is already connected, then immediately send
1983 * out a followup broadcast indicating successful failover
1984 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001985 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001986 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1987 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001988 }
1989 }
1990
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001991 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001992 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001993 * If this is a default network, check if other defaults are available.
1994 * Try to reconnect on all available and let them hash it out when
1995 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001996 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001997 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001998 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001999 if (DBG) {
2000 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2001 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002002 mActiveDefaultNetwork = -1;
2003 }
2004
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002005 // don't signal a reconnect for anything lower or equal priority than our
2006 // current connected default
2007 // TODO - don't filter by priority now - nice optimization but risky
2008// int currentPriority = -1;
2009// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002010// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002011// }
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002012
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002013 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07002014 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002015 if (mNetConfigs[checkType] == null) continue;
2016 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08002017 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08002018
2019// Enabling the isAvailable() optimization caused mobile to not get
2020// selected if it was in the middle of error handling. Specifically
2021// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2022// would not be available and we wouldn't get connected to anything.
2023// So removing the isAvailable() optimization below for now. TODO: This
2024// optimization should work and we need to investigate why it doesn't work.
2025// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2026// complete before it is really complete.
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002027
Wink Saville72a95b92011-01-26 15:43:49 -08002028// if (!mNetTrackers[checkType].isAvailable()) continue;
2029
Robert Greenwalt34848c02011-03-25 13:09:25 -07002030// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002031
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002032 NetworkStateTracker checkTracker = mNetTrackers[checkType];
2033 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2034 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2035 checkInfo.setFailover(true);
2036 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002037 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002038 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002039 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002040 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002041 }
2042
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002043 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002044 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07002045 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2046 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002047 }
2048
Wink Saville4f0de1e2011-08-04 15:01:58 -07002049 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002050 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2051 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002052 }
2053
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002054 private void sendInetConditionBroadcast(NetworkInfo info) {
2055 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2056 }
2057
Wink Saville4f0de1e2011-08-04 15:01:58 -07002058 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002059 if (mLockdownTracker != null) {
2060 info = mLockdownTracker.augmentNetworkInfo(info);
2061 }
2062
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002063 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002064 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002065 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002066 if (info.isFailover()) {
2067 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2068 info.setFailover(false);
2069 }
2070 if (info.getReason() != null) {
2071 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2072 }
2073 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002074 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2075 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002076 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002077 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002078 return intent;
2079 }
2080
2081 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2082 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2083 }
2084
2085 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2086 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002087 }
2088
Haoyu Baib5da5752012-06-20 14:29:57 -07002089 private void sendDataActivityBroadcast(int deviceType, boolean active) {
2090 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2091 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2092 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002093 final long ident = Binder.clearCallingIdentity();
2094 try {
2095 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2096 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2097 } finally {
2098 Binder.restoreCallingIdentity(ident);
2099 }
Haoyu Baib5da5752012-06-20 14:29:57 -07002100 }
2101
The Android Open Source Project28527d22009-03-03 19:31:44 -08002102 /**
2103 * Called when an attempt to fail over to another network has failed.
2104 * @param info the {@link NetworkInfo} for the failed network
2105 */
2106 private void handleConnectionFailure(NetworkInfo info) {
2107 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002108
Robert Greenwalt2034b912009-08-12 16:08:25 -07002109 String reason = info.getReason();
2110 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07002111
Robert Greenwalte981bc52010-10-08 16:35:52 -07002112 String reasonText;
2113 if (reason == null) {
2114 reasonText = ".";
2115 } else {
2116 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08002117 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002118 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002119
2120 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002121 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002122 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002123 if (getActiveNetworkInfo() == null) {
2124 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2125 }
2126 if (reason != null) {
2127 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2128 }
2129 if (extraInfo != null) {
2130 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2131 }
2132 if (info.isFailover()) {
2133 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2134 info.setFailover(false);
2135 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002136
Robert Greenwalt34848c02011-03-25 13:09:25 -07002137 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002138 tryFailover(info.getType());
2139 if (mActiveDefaultNetwork != -1) {
2140 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002141 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2142 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002143 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002144 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2145 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002146 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002147
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002148 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002149
2150 final Intent immediateIntent = new Intent(intent);
2151 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2152 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002153 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002154 /*
2155 * If the failover network is already connected, then immediately send
2156 * out a followup broadcast indicating successful failover
2157 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002158 if (mActiveDefaultNetwork != -1) {
2159 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002160 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002161 }
2162
2163 private void sendStickyBroadcast(Intent intent) {
2164 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002165 if (!mSystemReady) {
2166 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002167 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002168 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002169 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002170 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002171 }
2172
Dianne Hackborne588ca12012-09-04 18:48:37 -07002173 final long ident = Binder.clearCallingIdentity();
2174 try {
2175 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2176 } finally {
2177 Binder.restoreCallingIdentity(ident);
2178 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002179 }
2180 }
2181
Wink Saville4f0de1e2011-08-04 15:01:58 -07002182 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2183 if (delayMs <= 0) {
2184 sendStickyBroadcast(intent);
2185 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002186 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002187 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2188 + intent.getAction());
2189 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002190 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2191 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2192 }
2193 }
2194
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002195 void systemReady() {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002196 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2197 loadGlobalProxy();
2198
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002199 synchronized(this) {
2200 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002201 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002202 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002203 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002204 }
2205 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002206 // load the global proxy at startup
2207 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002208
2209 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2210 // for user to unlock device.
2211 if (!updateLockdownVpn()) {
2212 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2213 mContext.registerReceiver(mUserPresentReceiver, filter);
2214 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002215 }
2216
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002217 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2218 @Override
2219 public void onReceive(Context context, Intent intent) {
2220 // Try creating lockdown tracker, since user present usually means
2221 // unlocked keystore.
2222 if (updateLockdownVpn()) {
2223 mContext.unregisterReceiver(this);
2224 }
2225 }
2226 };
2227
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002228 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002229 if (((type != mNetworkPreference)
2230 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2231 || (mNetworkPreference == mActiveDefaultNetwork)) {
2232 return false;
2233 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002234 return true;
2235 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002236
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002237 private void handleConnect(NetworkInfo info) {
2238 final int newNetType = info.getType();
2239
2240 setupDataActivityTracking(newNetType);
Haoyu Baie2462442012-06-28 15:26:19 -07002241
The Android Open Source Project28527d22009-03-03 19:31:44 -08002242 // snapshot isFailover, because sendConnectedBroadcast() resets it
2243 boolean isFailover = info.isFailover();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002244 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002245 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002246
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002247 if (VDBG) {
2248 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2249 + " isFailover" + isFailover);
2250 }
2251
Robert Greenwalt2034b912009-08-12 16:08:25 -07002252 // if this is a default net and other default is running
2253 // kill the one not preferred
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002254 if (mNetConfigs[newNetType].isDefault()) {
2255 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2256 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002257 // tear down the other
2258 NetworkStateTracker otherNet =
2259 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002260 if (DBG) {
2261 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002262 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002263 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002264 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002265 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002266 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002267 return;
2268 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002269 } else {
2270 // don't accept this one
2271 if (VDBG) {
2272 log("Not broadcasting CONNECT_ACTION " +
2273 "to torn down network " + info.getTypeName());
2274 }
2275 teardown(thisNet);
2276 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002277 }
2278 }
2279 synchronized (ConnectivityService.this) {
2280 // have a new default network, release the transition wakelock in a second
2281 // if it's held. The second pause is to allow apps to reconnect over the
2282 // new network
2283 if (mNetTransitionWakeLock.isHeld()) {
2284 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002285 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002286 mNetTransitionWakeLockSerialNumber, 0),
2287 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002288 }
2289 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002290 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002291 // this will cause us to come up initially as unconnected and switching
2292 // to connected after our normal pause unless somebody reports us as reall
2293 // disconnected
2294 mDefaultInetConditionPublished = 0;
2295 mDefaultConnectionSequence++;
2296 mInetConditionChangeInFlight = false;
2297 // Don't do this - if we never sign in stay, grey
2298 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002299 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002300 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002301 updateNetworkSettings(thisNet);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002302 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002303 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002304
2305 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002306 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002307 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002308 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002309 } catch (RemoteException e) {
2310 // ignored; service lives in system_server
2311 }
2312 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002313 }
2314
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002315 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2316 if (DBG) log("Captive portal check " + info);
2317 int type = info.getType();
2318 final NetworkStateTracker thisNet = mNetTrackers[type];
2319 if (mNetConfigs[type].isDefault()) {
2320 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2321 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2322 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002323 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002324 return;
2325 } else {
2326 if (DBG) log("Tear down low priority net " + info.getTypeName());
2327 teardown(thisNet);
2328 return;
2329 }
2330 }
2331 }
2332
Wink Saville674777e2013-08-07 16:22:47 -07002333 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002334 thisNet.captivePortalCheckComplete();
2335 }
2336
2337 /** @hide */
Wink Saville674777e2013-08-07 16:22:47 -07002338 @Override
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002339 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002340 enforceConnectivityInternalPermission();
Wink Saville674777e2013-08-07 16:22:47 -07002341 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002342 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002343 }
2344
Wink Saville674777e2013-08-07 16:22:47 -07002345 /** @hide */
2346 @Override
2347 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2348 enforceConnectivityInternalPermission();
2349 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2350 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2351 }
2352
The Android Open Source Project28527d22009-03-03 19:31:44 -08002353 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002354 * Setup data activity tracking for the given network interface.
2355 *
2356 * Every {@code setupDataActivityTracking} should be paired with a
2357 * {@link removeDataActivityTracking} for cleanup.
2358 */
2359 private void setupDataActivityTracking(int type) {
2360 final NetworkStateTracker thisNet = mNetTrackers[type];
2361 final String iface = thisNet.getLinkProperties().getInterfaceName();
2362
2363 final int timeout;
2364
2365 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002366 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2367 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Baie2462442012-06-28 15:26:19 -07002368 0);
2369 // Canonicalize mobile network type
2370 type = ConnectivityManager.TYPE_MOBILE;
2371 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002372 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2373 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Baie2462442012-06-28 15:26:19 -07002374 0);
2375 } else {
2376 // do not track any other networks
2377 timeout = 0;
2378 }
2379
2380 if (timeout > 0 && iface != null) {
2381 try {
2382 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2383 } catch (RemoteException e) {
2384 }
2385 }
2386 }
2387
2388 /**
2389 * Remove data activity tracking when network disconnects.
2390 */
2391 private void removeDataActivityTracking(int type) {
2392 final NetworkStateTracker net = mNetTrackers[type];
2393 final String iface = net.getLinkProperties().getInterfaceName();
2394
2395 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2396 ConnectivityManager.TYPE_WIFI == type)) {
2397 try {
2398 // the call fails silently if no idletimer setup for this interface
2399 mNetd.removeIdleTimer(iface);
2400 } catch (RemoteException e) {
2401 }
2402 }
2403 }
2404
2405 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002406 * After a change in the connectivity state of a network. We're mainly
2407 * concerned with making sure that the list of DNS servers is set up
2408 * according to which networks are connected, and ensuring that the
2409 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002410 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002411 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002412 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubaker49db4222013-07-15 16:34:04 -07002413 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002414 if (VDBG) {
2415 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2416 + " resetMask=" + resetMask);
2417 }
Wink Saville051a6642011-07-13 13:44:13 -07002418
The Android Open Source Project28527d22009-03-03 19:31:44 -08002419 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002420 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002421 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002422 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002423 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002424
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002425 LinkProperties curLp = mCurrentLinkProperties[netType];
2426 LinkProperties newLp = null;
2427
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002428 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002429 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002430 if (VDBG) {
2431 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2432 " doReset=" + doReset + " resetMask=" + resetMask +
2433 "\n curLp=" + curLp +
2434 "\n newLp=" + newLp);
2435 }
2436
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002437 if (curLp != null) {
2438 if (curLp.isIdenticalInterfaceName(newLp)) {
2439 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2440 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2441 for (LinkAddress linkAddr : car.removed) {
2442 if (linkAddr.getAddress() instanceof Inet4Address) {
2443 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2444 }
2445 if (linkAddr.getAddress() instanceof Inet6Address) {
2446 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2447 }
Wink Saville051a6642011-07-13 13:44:13 -07002448 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002449 if (DBG) {
2450 log("handleConnectivityChange: addresses changed" +
2451 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2452 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002453 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002454 } else {
2455 if (DBG) {
2456 log("handleConnectivityChange: address are the same reset per doReset" +
2457 " linkProperty[" + netType + "]:" +
2458 " resetMask=" + resetMask);
2459 }
Wink Saville051a6642011-07-13 13:44:13 -07002460 }
2461 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002462 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002463 if (DBG) {
2464 log("handleConnectivityChange: interface not not equivalent reset both" +
2465 " linkProperty[" + netType + "]:" +
2466 " resetMask=" + resetMask);
2467 }
Wink Saville051a6642011-07-13 13:44:13 -07002468 }
Wink Saville051a6642011-07-13 13:44:13 -07002469 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002470 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002471 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002472 }
2473 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002474 if (VDBG) {
2475 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2476 " doReset=" + doReset + " resetMask=" + resetMask +
2477 "\n curLp=" + curLp +
2478 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002479 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002480 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002481 mCurrentLinkProperties[netType] = newLp;
Chad Brubaker49db4222013-07-15 16:34:04 -07002482 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002483
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002484 if (resetMask != 0 || resetDns) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002485 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwalt4398f342013-05-23 18:33:06 -07002486 if (curLp != null) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002487 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwalt4398f342013-05-23 18:33:06 -07002488 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti63839822013-03-20 19:22:58 +09002489 if (TextUtils.isEmpty(iface) == false) {
2490 if (resetMask != 0) {
2491 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2492 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002493
Lorenzo Colitti63839822013-03-20 19:22:58 +09002494 // Tell VPN the interface is down. It is a temporary
2495 // but effective fix to make VPN aware of the change.
2496 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07002497 synchronized(mVpns) {
2498 for (int i = 0; i < mVpns.size(); i++) {
2499 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2500 }
2501 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002502 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002503 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002504 if (resetDns) {
2505 flushVmDnsCache();
2506 if (VDBG) log("resetting DNS cache for " + iface);
2507 try {
2508 mNetd.flushInterfaceDnsCache(iface);
2509 } catch (Exception e) {
2510 // never crash - catch them all
2511 if (DBG) loge("Exception resetting dns cache: " + e);
2512 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002513 }
Robert Greenwalt4398f342013-05-23 18:33:06 -07002514 } else {
2515 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002516 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002517 }
2518 }
2519 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002520
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002521 // Update 464xlat state.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002522 NetworkStateTracker tracker = mNetTrackers[netType];
2523 if (mClat.requiresClat(netType, tracker)) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002524
Lorenzo Colitti4118d082013-03-28 14:13:43 +09002525 // If the connection was previously using clat, but is not using it now, stop the clat
2526 // daemon. Normally, this happens automatically when the connection disconnects, but if
2527 // the disconnect is not reported, or if the connection's LinkProperties changed for
2528 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2529 // still be running. If it's not running, then stopping it is a no-op.
2530 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2531 mClat.stopClat();
2532 }
2533 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002534 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2535 mClat.startClat(tracker);
2536 } else {
2537 mClat.stopClat();
2538 }
2539 }
2540
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002541 // TODO: Temporary notifying upstread change to Tethering.
2542 // @see bug/4455071
2543 /** Notify TetheringService if interface name has been changed. */
2544 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002545 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002546 if (isTetheringSupported()) {
2547 mTethering.handleTetherIfaceChange();
2548 }
2549 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002550 }
2551
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002552 /**
2553 * Add and remove routes using the old properties (null if not previously connected),
2554 * new properties (null if becoming disconnected). May even be double null, which
2555 * is a noop.
2556 * Uses isLinkDefault to determine if default routes should be set or conversely if
2557 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002558 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002559 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002560 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubaker49db4222013-07-15 16:34:04 -07002561 boolean isLinkDefault, boolean exempt) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002562 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002563 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2564 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002565 if (curLp != null) {
2566 // check for the delta between the current set and the new
Lorenzo Colittie1b47422013-07-31 23:23:21 +09002567 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002568 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002569 } else if (newLp != null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002570 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002571 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002572 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002573
Robert Greenwalt8d777252011-08-15 12:31:55 -07002574 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2575
Robert Greenwalt98107422011-07-22 11:55:33 -07002576 for (RouteInfo r : routeDiff.removed) {
2577 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002578 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002579 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2580 }
2581 if (isLinkDefault == false) {
2582 // remove from a secondary route table
2583 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002584 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002585 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002586
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002587 if (!isLinkDefault) {
2588 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002589 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002590 // routes changed - remove all old dns entries and add new
2591 if (curLp != null) {
2592 for (InetAddress oldDns : curLp.getDnses()) {
2593 removeRouteToAddress(curLp, oldDns);
2594 }
2595 }
2596 if (newLp != null) {
2597 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002598 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07002599 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002600 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002601 } else {
2602 // no change in routes, check for change in dns themselves
2603 for (InetAddress oldDns : dnsDiff.removed) {
2604 removeRouteToAddress(curLp, oldDns);
2605 }
2606 for (InetAddress newDns : dnsDiff.added) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002607 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002608 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002609 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002610 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002611
2612 for (RouteInfo r : routeDiff.added) {
2613 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002614 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002615 } else {
2616 // add to a secondary route table
Chad Brubaker49db4222013-07-15 16:34:04 -07002617 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002618
2619 // many radios add a default route even when we don't want one.
2620 // remove the default route unless somebody else has asked for it
2621 String ifaceName = newLp.getInterfaceName();
Chad Brubaker49db4222013-07-15 16:34:04 -07002622 synchronized (mRoutesLock) {
2623 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2624 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2625 try {
2626 mNetd.removeRoute(ifaceName, r);
2627 } catch (Exception e) {
2628 // never crash - catch them all
2629 if (DBG) loge("Exception trying to remove a route: " + e);
2630 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002631 }
2632 }
2633 }
2634 }
2635
Robert Greenwalt8d777252011-08-15 12:31:55 -07002636 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002637 }
2638
2639
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002640 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002641 * Reads the network specific TCP buffer sizes from SystemProperties
2642 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2643 * wide use
2644 */
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002645 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002646 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002647 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002648
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002649 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002650 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002651
2652 // Setting to default values so we won't be stuck to previous values
2653 key = "net.tcp.buffersize.default";
2654 bufferSizes = SystemProperties.get(key);
2655 }
2656
2657 // Set values in kernel
2658 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002659 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002660 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002661 + "] which comes from [" + key + "]");
2662 }
2663 setBufferSize(bufferSizes);
2664 }
2665 }
2666
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002667 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002668 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2669 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2670 *
2671 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2672 * writeMin, writeInitial, writeMax"
2673 */
2674 private void setBufferSize(String bufferSizes) {
2675 try {
2676 String[] values = bufferSizes.split(",");
2677
2678 if (values.length == 6) {
2679 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002680 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2681 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2682 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2683 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2684 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2685 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002686 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002687 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002688 }
2689 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002690 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002691 }
2692 }
2693
Robert Greenwalt2034b912009-08-12 16:08:25 -07002694 /**
2695 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2696 * on the highest priority active net which this process requested.
2697 * If there aren't any, clear it out
2698 */
Mattias Falkd697aa22011-08-23 14:15:13 +02002699 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002700 {
Mattias Falkd697aa22011-08-23 14:15:13 +02002701 if (VDBG) log("reassessPidDns for pid " + pid);
2702 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002703 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002704 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002705 continue;
2706 }
2707 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002708 if (nt.getNetworkInfo().isConnected() &&
2709 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002710 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002711 if (p == null) continue;
Mattias Falkd697aa22011-08-23 14:15:13 +02002712 if (mNetRequestersPids[i].contains(myPid)) {
2713 try {
2714 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2715 } catch (Exception e) {
2716 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002717 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002718 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002719 }
2720 }
2721 }
2722 // nothing found - delete
Mattias Falkd697aa22011-08-23 14:15:13 +02002723 try {
2724 mNetd.clearDnsInterfaceForPid(pid);
2725 } catch (Exception e) {
2726 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002727 }
2728 }
2729
Mattias Falkd697aa22011-08-23 14:15:13 +02002730 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002731 /*
2732 * Tell the VMs to toss their DNS caches
2733 */
2734 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2735 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002736 /*
2737 * Connectivity events can happen before boot has completed ...
2738 */
2739 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002740 final long ident = Binder.clearCallingIdentity();
2741 try {
2742 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2743 } finally {
2744 Binder.restoreCallingIdentity(ident);
2745 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002746 }
2747
Chia-chi Yehcc844502011-07-14 18:01:57 -07002748 // Caller must grab mDnsLock.
Mattias Falkd697aa22011-08-23 14:15:13 +02002749 private void updateDnsLocked(String network, String iface,
Chad Brubaker73652d02013-07-23 17:13:36 -07002750 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002751 int last = 0;
2752 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002753 dnses = new ArrayList();
2754 dnses.add(mDefaultDns);
2755 if (DBG) {
2756 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002757 }
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002758 }
2759
Mattias Falkd697aa22011-08-23 14:15:13 +02002760 try {
2761 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker73652d02013-07-23 17:13:36 -07002762 if (defaultDns) {
2763 mNetd.setDefaultInterfaceForDns(iface);
2764 }
2765
Robert Greenwalte41e3b32013-02-11 15:25:10 -08002766 for (InetAddress dns : dnses) {
2767 ++last;
2768 String key = "net.dns" + last;
2769 String value = dns.getHostAddress();
2770 SystemProperties.set(key, value);
2771 }
2772 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2773 String key = "net.dns" + i;
2774 SystemProperties.set(key, "");
2775 }
2776 mNumDnsEntries = last;
Mattias Falkd697aa22011-08-23 14:15:13 +02002777 } catch (Exception e) {
2778 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002779 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002780 }
2781
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002782 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002783 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002784 NetworkStateTracker nt = mNetTrackers[netType];
2785 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002786 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002787 if (p == null) return;
2788 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002789 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002790 String network = nt.getNetworkInfo().getTypeName();
2791 synchronized (mDnsLock) {
Chad Brubaker5fdc1462013-07-23 17:44:41 -07002792 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002793 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002794 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002795 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002796 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltcd277852012-11-09 10:52:27 -08002797 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002798 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002799 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002800 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002801 // set per-pid dns for attached secondary nets
Mattias Falkd697aa22011-08-23 14:15:13 +02002802 List<Integer> pids = mNetRequestersPids[netType];
2803 for (Integer pid : pids) {
2804 try {
2805 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2806 } catch (Exception e) {
2807 Slog.e(TAG, "exception setting interface for pid: " + e);
2808 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002809 }
2810 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002811 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002812 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002813 }
2814
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002815 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002816 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2817 NETWORK_RESTORE_DELAY_PROP_NAME);
2818 if(restoreDefaultNetworkDelayStr != null &&
2819 restoreDefaultNetworkDelayStr.length() != 0) {
2820 try {
2821 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2822 } catch (NumberFormatException e) {
2823 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002824 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002825 // if the system property isn't set, use the value for the apn type
2826 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2827
2828 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2829 (mNetConfigs[networkType] != null)) {
2830 ret = mNetConfigs[networkType].restoreTime;
2831 }
2832 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002833 }
2834
2835 @Override
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002836 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2837 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002838 if (mContext.checkCallingOrSelfPermission(
2839 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002840 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002841 pw.println("Permission Denial: can't dump ConnectivityService " +
2842 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2843 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002844 return;
2845 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002846
2847 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002848 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002849 for (int i = 0; i < mNetTrackers.length; i++) {
2850 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002851 if (nst != null) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002852 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2853 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002854 if (nst.getNetworkInfo().isConnected()) {
2855 pw.println("Active network: " + nst.getNetworkInfo().
2856 getTypeName());
2857 }
2858 pw.println(nst.getNetworkInfo());
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002859 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002860 pw.println(nst);
2861 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002862 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002863 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002864 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002865
2866 pw.println("Network Requester Pids:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002867 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002868 for (int net : mPriorityList) {
2869 String pidString = net + ": ";
Mattias Falkd697aa22011-08-23 14:15:13 +02002870 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002871 pidString = pidString + pid.toString() + ", ";
2872 }
2873 pw.println(pidString);
2874 }
2875 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002876 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002877
2878 pw.println("FeatureUsers:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002879 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002880 for (Object requester : mFeatureUsers) {
2881 pw.println(requester.toString());
2882 }
2883 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002884 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002885
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002886 synchronized (this) {
2887 pw.println("NetworkTranstionWakeLock is currently " +
2888 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2889 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2890 }
2891 pw.println();
2892
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002893 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002894
2895 if (mInetLog != null) {
2896 pw.println();
2897 pw.println("Inet condition reports:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002898 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002899 for(int i = 0; i < mInetLog.size(); i++) {
2900 pw.println(mInetLog.get(i));
2901 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002902 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002903 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002904 }
2905
Robert Greenwalt2034b912009-08-12 16:08:25 -07002906 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002907 private class NetworkStateTrackerHandler extends Handler {
2908 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002909 super(looper);
2910 }
2911
The Android Open Source Project28527d22009-03-03 19:31:44 -08002912 @Override
2913 public void handleMessage(Message msg) {
2914 NetworkInfo info;
2915 switch (msg.what) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002916 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002917 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002918 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002919
Wink Savillea7d56572011-09-21 11:05:43 -07002920 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Savilleb1a32022013-09-05 12:02:25 -07002921 (state == NetworkInfo.State.DISCONNECTED) ||
2922 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillea7d56572011-09-21 11:05:43 -07002923 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002924 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002925 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002926 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002927
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002928 // Since mobile has the notion of a network/apn that can be used for
2929 // provisioning we need to check every time we're connected as
2930 // CaptiveProtalTracker won't detected it because DCT doesn't report it
2931 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2932 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2933 // is received by MDST and sent here as EVENT_STATE_CHANGED.
2934 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Savillef0e9c7f2013-07-16 17:16:37 -07002935 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2936 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Savilleb1a32022013-09-05 12:02:25 -07002937 && ((state == NetworkInfo.State.CONNECTED)
2938 || info.isConnectedToProvisioningNetwork())) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002939 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Savillef0e9c7f2013-07-16 17:16:37 -07002940 }
2941
Jeff Sharkey876ddc92012-11-09 15:57:02 -08002942 EventLogTags.writeConnectivityStateChanged(
2943 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002944
2945 if (info.getDetailedState() ==
2946 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002947 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002948 } else if (info.getDetailedState() ==
2949 DetailedState.CAPTIVE_PORTAL_CHECK) {
2950 handleCaptivePortalTrackerCheck(info);
Wink Savilleb1a32022013-09-05 12:02:25 -07002951 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002952 /**
2953 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2954 * for now its an in between network, its a network that
2955 * is actually a default network but we don't want it to be
2956 * announced as such to keep background applications from
2957 * trying to use it. It turns out that some still try so we
2958 * take the additional step of clearing any default routes
2959 * to the link that may have incorrectly setup by the lower
2960 * levels.
2961 */
2962 LinkProperties lp = getLinkProperties(info.getType());
2963 if (DBG) {
2964 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2965 }
2966
2967 // Clear any default routes setup by the radio so
2968 // any activity by applications trying to use this
2969 // connection will fail until the provisioning network
2970 // is enabled.
2971 for (RouteInfo r : lp.getRoutes()) {
2972 removeRoute(lp, r, TO_DEFAULT_TABLE);
2973 }
Robert Greenwalt12c44552009-12-07 11:33:18 -08002974 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002975 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002976 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002977 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002978 // the logic here is, handle SUSPENDED the same as
2979 // DISCONNECTED. The only difference being we are
2980 // broadcasting an intent with NetworkInfo that's
2981 // suspended. This allows the applications an
2982 // opportunity to handle DISCONNECTED and SUSPENDED
2983 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002984 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002985 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002986 handleConnect(info);
2987 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002988 if (mLockdownTracker != null) {
2989 mLockdownTracker.onNetworkInfoChanged(info);
2990 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002991 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002992 }
2993 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002994 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002995 // TODO: Temporary allowing network configuration
2996 // change not resetting sockets.
2997 // @see bug/4455071
2998 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002999 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003000 }
3001 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07003002 info = (NetworkInfo) msg.obj;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003003 int type = info.getType();
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07003004 updateNetworkSettings(mNetTrackers[type]);
3005 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003006 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003007 }
3008 }
3009 }
3010
3011 private class InternalHandler extends Handler {
3012 public InternalHandler(Looper looper) {
3013 super(looper);
3014 }
3015
3016 @Override
3017 public void handleMessage(Message msg) {
3018 NetworkInfo info;
3019 switch (msg.what) {
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003020 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003021 String causedBy = null;
3022 synchronized (ConnectivityService.this) {
3023 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3024 mNetTransitionWakeLock.isHeld()) {
3025 mNetTransitionWakeLock.release();
3026 causedBy = mNetTransitionWakeLockCausedBy;
3027 }
3028 }
3029 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003030 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003031 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07003032 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003033 }
3034 case EVENT_RESTORE_DEFAULT_NETWORK: {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003035 FeatureUser u = (FeatureUser)msg.obj;
3036 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003037 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003038 }
3039 case EVENT_INET_CONDITION_CHANGE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003040 int netType = msg.arg1;
3041 int condition = msg.arg2;
3042 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003043 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003044 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003045 case EVENT_INET_CONDITION_HOLD_END: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003046 int netType = msg.arg1;
3047 int sequence = msg.arg2;
Wink Saville151eaa62013-01-31 00:30:13 +00003048 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07003049 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003050 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003051 case EVENT_SET_NETWORK_PREFERENCE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003052 int preference = msg.arg1;
3053 handleSetNetworkPreference(preference);
3054 break;
3055 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003056 case EVENT_SET_MOBILE_DATA: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003057 boolean enabled = (msg.arg1 == ENABLED);
3058 handleSetMobileData(enabled);
3059 break;
3060 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003061 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003062 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07003063 break;
3064 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003065 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwalt34848c02011-03-25 13:09:25 -07003066 boolean met = (msg.arg1 == ENABLED);
3067 handleSetDependencyMet(msg.arg2, met);
3068 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003069 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003070 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville4f0de1e2011-08-04 15:01:58 -07003071 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07003072 sendStickyBroadcast(intent);
3073 break;
3074 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07003075 case EVENT_SET_POLICY_DATA_ENABLE: {
3076 final int networkType = msg.arg1;
3077 final boolean enabled = msg.arg2 == ENABLED;
3078 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003079 break;
3080 }
3081 case EVENT_VPN_STATE_CHANGED: {
3082 if (mLockdownTracker != null) {
3083 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3084 }
3085 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07003086 }
Wink Saville32506bc2013-06-29 21:10:57 -07003087 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3088 int tag = mEnableFailFastMobileDataTag.get();
3089 if (msg.arg1 == tag) {
3090 MobileDataStateTracker mobileDst =
3091 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3092 if (mobileDst != null) {
3093 mobileDst.setEnableFailFastMobileData(msg.arg2);
3094 }
3095 } else {
3096 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3097 + " != tag:" + tag);
3098 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003099 break;
Wink Saville32506bc2013-06-29 21:10:57 -07003100 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003101 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07003102 handleNetworkSamplingTimeout();
3103 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003104 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003105 }
3106 }
3107 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003108
3109 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003110 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003111 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003112
3113 if (isTetheringSupported()) {
3114 return mTethering.tether(iface);
3115 } else {
3116 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3117 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003118 }
3119
3120 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003121 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003122 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003123
3124 if (isTetheringSupported()) {
3125 return mTethering.untether(iface);
3126 } else {
3127 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3128 }
3129 }
3130
3131 // javadoc from interface
3132 public int getLastTetherError(String iface) {
3133 enforceTetherAccessPermission();
3134
3135 if (isTetheringSupported()) {
3136 return mTethering.getLastTetherError(iface);
3137 } else {
3138 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3139 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003140 }
3141
3142 // TODO - proper iface API for selection by property, inspection, etc
3143 public String[] getTetherableUsbRegexs() {
3144 enforceTetherAccessPermission();
3145 if (isTetheringSupported()) {
3146 return mTethering.getTetherableUsbRegexs();
3147 } else {
3148 return new String[0];
3149 }
3150 }
3151
3152 public String[] getTetherableWifiRegexs() {
3153 enforceTetherAccessPermission();
3154 if (isTetheringSupported()) {
3155 return mTethering.getTetherableWifiRegexs();
3156 } else {
3157 return new String[0];
3158 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003159 }
3160
Danica Chang96567052010-08-11 14:54:43 -07003161 public String[] getTetherableBluetoothRegexs() {
3162 enforceTetherAccessPermission();
3163 if (isTetheringSupported()) {
3164 return mTethering.getTetherableBluetoothRegexs();
3165 } else {
3166 return new String[0];
3167 }
3168 }
3169
Mike Lockwooded4a1742011-07-19 13:04:47 -07003170 public int setUsbTethering(boolean enable) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003171 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07003172 if (isTetheringSupported()) {
3173 return mTethering.setUsbTethering(enable);
3174 } else {
3175 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3176 }
3177 }
3178
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003179 // TODO - move iface listing, queries, etc to new module
3180 // javadoc from interface
3181 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003182 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003183 return mTethering.getTetherableIfaces();
3184 }
3185
3186 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003187 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003188 return mTethering.getTetheredIfaces();
3189 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003190
Jeff Sharkey300f08f2011-09-16 01:52:49 -07003191 @Override
3192 public String[] getTetheredIfacePairs() {
3193 enforceTetherAccessPermission();
3194 return mTethering.getTetheredIfacePairs();
3195 }
3196
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003197 public String[] getTetheringErroredIfaces() {
3198 enforceTetherAccessPermission();
3199 return mTethering.getErroredIfaces();
3200 }
3201
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003202 // if ro.tether.denied = true we default to no tethering
3203 // gservices could set the secure setting to 1 though to enable it on a build where it
3204 // had previously been turned off.
3205 public boolean isTetheringSupported() {
3206 enforceTetherAccessPermission();
3207 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownc67cf562012-09-25 15:03:20 -07003208 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3209 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt368095f2013-07-18 14:24:42 -07003210 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3211 mTethering.getTetherableWifiRegexs().length != 0 ||
3212 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3213 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003214 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003215
3216 // An API NetworkStateTrackers can call when they lose their network.
3217 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3218 // whichever happens first. The timer is started by the first caller and not
3219 // restarted by subsequent callers.
3220 public void requestNetworkTransitionWakelock(String forWhom) {
3221 enforceConnectivityInternalPermission();
3222 synchronized (this) {
3223 if (mNetTransitionWakeLock.isHeld()) return;
3224 mNetTransitionWakeLockSerialNumber++;
3225 mNetTransitionWakeLock.acquire();
3226 mNetTransitionWakeLockCausedBy = forWhom;
3227 }
3228 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003229 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003230 mNetTransitionWakeLockSerialNumber, 0),
3231 mNetTransitionWakeLockTimeout);
3232 return;
3233 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003234
Robert Greenwalt986c7412010-09-08 15:24:47 -07003235 // 100 percent is full good, 0 is full bad.
3236 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003237 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003238 mContext.enforceCallingOrSelfPermission(
3239 android.Manifest.permission.STATUS_BAR,
3240 "ConnectivityService");
3241
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003242 if (DBG) {
3243 int pid = getCallingPid();
3244 int uid = getCallingUid();
3245 String s = pid + "(" + uid + ") reports inet is " +
3246 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3247 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3248 mInetLog.add(s);
3249 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3250 mInetLog.remove(0);
3251 }
3252 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003253 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003254 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3255 }
3256
3257 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003258 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003259 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003260 return;
3261 }
3262 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003263 if (DBG) log("handleInetConditionChange: net=" + netType +
3264 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003265 return;
3266 }
Wink Savillea7d56572011-09-21 11:05:43 -07003267 if (VDBG) {
3268 log("handleInetConditionChange: net=" +
3269 netType + ", condition=" + condition +
Wink Saville151eaa62013-01-31 00:30:13 +00003270 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003271 }
Wink Saville151eaa62013-01-31 00:30:13 +00003272 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003273 int delay;
3274 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003275 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003276 // setup a new hold to debounce this
Wink Saville151eaa62013-01-31 00:30:13 +00003277 if (mDefaultInetCondition > 50) {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003278 delay = Settings.Global.getInt(mContext.getContentResolver(),
3279 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003280 } else {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003281 delay = Settings.Global.getInt(mContext.getContentResolver(),
3282 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003283 }
3284 mInetConditionChangeInFlight = true;
3285 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville151eaa62013-01-31 00:30:13 +00003286 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003287 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003288 // we've set the new condition, when this hold ends that will get picked up
3289 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003290 }
3291 }
3292
Wink Saville151eaa62013-01-31 00:30:13 +00003293 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003294 if (DBG) {
Wink Saville151eaa62013-01-31 00:30:13 +00003295 log("handleInetConditionHoldEnd: net=" + netType +
3296 ", condition=" + mDefaultInetCondition +
3297 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003298 }
3299 mInetConditionChangeInFlight = false;
3300
3301 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003302 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003303 return;
3304 }
3305 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003306 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003307 return;
3308 }
Wink Saville151eaa62013-01-31 00:30:13 +00003309 // TODO: Figure out why this optimization sometimes causes a
3310 // change in mDefaultInetCondition to be missed and the
3311 // UI to not be updated.
3312 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3313 // if (DBG) log("no change in condition - aborting");
3314 // return;
3315 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003316 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3317 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003318 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003319 return;
3320 }
Wink Saville151eaa62013-01-31 00:30:13 +00003321 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003322 sendInetConditionBroadcast(networkInfo);
3323 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003324 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003325
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003326 public ProxyProperties getProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003327 // this information is already available as a world read/writable jvm property
3328 // so this API change wouldn't have a benifit. It also breaks the passing
3329 // of proxy info to all the JVMs.
3330 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003331 synchronized (mProxyLock) {
Jason Monka5bf2842013-07-03 17:04:33 -04003332 ProxyProperties ret = mGlobalProxy;
3333 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3334 return ret;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003335 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003336 }
3337
3338 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003339 enforceConnectivityInternalPermission();
Jason Monka5bf2842013-07-03 17:04:33 -04003340
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003341 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003342 if (proxyProperties == mGlobalProxy) return;
3343 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3344 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3345
3346 String host = "";
3347 int port = 0;
3348 String exclList = "";
Jason Monka5bf2842013-07-03 17:04:33 -04003349 String pacFileUrl = "";
3350 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3351 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003352 mGlobalProxy = new ProxyProperties(proxyProperties);
3353 host = mGlobalProxy.getHost();
3354 port = mGlobalProxy.getPort();
3355 exclList = mGlobalProxy.getExclusionList();
Jason Monka5bf2842013-07-03 17:04:33 -04003356 if (proxyProperties.getPacFileUrl() != null) {
3357 pacFileUrl = proxyProperties.getPacFileUrl();
3358 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003359 } else {
3360 mGlobalProxy = null;
3361 }
3362 ContentResolver res = mContext.getContentResolver();
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003363 final long token = Binder.clearCallingIdentity();
3364 try {
3365 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3366 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3367 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3368 exclList);
Jason Monka5bf2842013-07-03 17:04:33 -04003369 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003370 } finally {
3371 Binder.restoreCallingIdentity(token);
3372 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003373 }
3374
3375 if (mGlobalProxy == null) {
3376 proxyProperties = mDefaultProxy;
3377 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003378 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003379 }
3380
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003381 private void loadGlobalProxy() {
3382 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003383 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3384 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3385 String exclList = Settings.Global.getString(res,
3386 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monka5bf2842013-07-03 17:04:33 -04003387 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3388 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3389 ProxyProperties proxyProperties;
3390 if (!TextUtils.isEmpty(pacFileUrl)) {
3391 proxyProperties = new ProxyProperties(pacFileUrl);
3392 } else {
3393 proxyProperties = new ProxyProperties(host, port, exclList);
3394 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003395 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003396 mGlobalProxy = proxyProperties;
3397 }
3398 }
3399 }
3400
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003401 public ProxyProperties getGlobalProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003402 // this information is already available as a world read/writable jvm property
3403 // so this API change wouldn't have a benifit. It also breaks the passing
3404 // of proxy info to all the JVMs.
3405 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003406 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003407 return mGlobalProxy;
3408 }
3409 }
3410
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003411 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04003412 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3413 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003414 proxy = null;
3415 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003416 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003417 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003418 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003419 mDefaultProxy = proxy;
3420
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003421 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003422 if (!mDefaultProxyDisabled) {
3423 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003424 }
3425 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003426 }
3427
3428 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003429 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3430 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003431 if (!TextUtils.isEmpty(proxy)) {
3432 String data[] = proxy.split(":");
Andreas Huber23bff232013-05-28 15:17:37 -07003433 if (data.length == 0) {
3434 return;
3435 }
3436
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003437 String proxyHost = data[0];
3438 int proxyPort = 8080;
3439 if (data.length > 1) {
3440 try {
3441 proxyPort = Integer.parseInt(data[1]);
3442 } catch (NumberFormatException e) {
3443 return;
3444 }
3445 }
3446 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3447 setGlobalProxy(p);
3448 }
3449 }
3450
3451 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003452 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monka5bf2842013-07-03 17:04:33 -04003453 mPacManager.setCurrentProxyScriptUrl(proxy);
Robert Greenwalt78f28112011-08-02 17:18:41 -07003454 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003455 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003456 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3457 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003458 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003459 final long ident = Binder.clearCallingIdentity();
3460 try {
3461 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3462 } finally {
3463 Binder.restoreCallingIdentity(ident);
3464 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003465 }
3466
3467 private static class SettingsObserver extends ContentObserver {
3468 private int mWhat;
3469 private Handler mHandler;
3470 SettingsObserver(Handler handler, int what) {
3471 super(handler);
3472 mHandler = handler;
3473 mWhat = what;
3474 }
3475
3476 void observe(Context context) {
3477 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003478 resolver.registerContentObserver(Settings.Global.getUriFor(
3479 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003480 }
3481
3482 @Override
3483 public void onChange(boolean selfChange) {
3484 mHandler.obtainMessage(mWhat).sendToTarget();
3485 }
3486 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003487
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003488 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003489 Slog.d(TAG, s);
3490 }
3491
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003492 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003493 Slog.e(TAG, s);
3494 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003495
repo syncf5de5572011-07-29 23:55:49 -07003496 int convertFeatureToNetworkType(int networkType, String feature) {
3497 int usedNetworkType = networkType;
3498
3499 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3500 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3501 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3502 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3503 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3504 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3505 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3506 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3507 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3508 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3509 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3510 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3511 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3512 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3513 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3514 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3515 } else {
3516 Slog.e(TAG, "Can't match any mobile netTracker!");
3517 }
3518 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3519 if (TextUtils.equals(feature, "p2p")) {
3520 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3521 } else {
3522 Slog.e(TAG, "Can't match any wifi netTracker!");
3523 }
3524 } else {
3525 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003526 }
repo syncf5de5572011-07-29 23:55:49 -07003527 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003528 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003529
3530 private static <T> T checkNotNull(T value, String message) {
3531 if (value == null) {
3532 throw new NullPointerException(message);
3533 }
3534 return value;
3535 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003536
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003537 /**
3538 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003539 * VpnBuilder and not available in ConnectivityManager. Permissions
3540 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003541 * @hide
3542 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003543 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003544 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003545 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003546 try {
3547 int type = mActiveDefaultNetwork;
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003548 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt15a41532012-08-21 19:27:00 -07003549 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003550 synchronized(mVpns) {
3551 mVpns.get(user).protect(socket,
3552 mNetTrackers[type].getLinkProperties().getInterfaceName());
3553 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003554 return true;
3555 }
3556 } catch (Exception e) {
3557 // ignore
3558 } finally {
3559 try {
3560 socket.close();
3561 } catch (Exception e) {
3562 // ignore
3563 }
3564 }
3565 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003566 }
3567
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003568 /**
3569 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003570 * and not available in ConnectivityManager. Permissions are checked
3571 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003572 * @hide
3573 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003574 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003575 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003576 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003577 int user = UserHandle.getUserId(Binder.getCallingUid());
3578 synchronized(mVpns) {
3579 return mVpns.get(user).prepare(oldPackage, newPackage);
3580 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003581 }
3582
Chad Brubaker11f22252013-07-11 13:29:30 -07003583 @Override
3584 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3585 enforceMarkNetworkSocketPermission();
3586 final long token = Binder.clearCallingIdentity();
3587 try {
3588 int mark = mNetd.getMarkForUid(uid);
3589 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3590 if (mark == -1) {
3591 mark = 0;
3592 }
3593 NetworkUtils.markSocket(socket.getFd(), mark);
3594 } catch (RemoteException e) {
3595 } finally {
3596 Binder.restoreCallingIdentity(token);
3597 }
3598 }
3599
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003600 /**
3601 * Configure a TUN interface and return its file descriptor. Parameters
3602 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003603 * and not available in ConnectivityManager. Permissions are checked in
3604 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003605 * @hide
3606 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003607 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003608 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003609 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003610 int user = UserHandle.getUserId(Binder.getCallingUid());
3611 synchronized(mVpns) {
3612 return mVpns.get(user).establish(config);
3613 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003614 }
3615
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003616 /**
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003617 * Start legacy VPN, controlling native daemons as needed. Creates a
3618 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003619 */
3620 @Override
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003621 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003622 throwIfLockdownEnabled();
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003623 final LinkProperties egress = getActiveLinkProperties();
3624 if (egress == null) {
3625 throw new IllegalStateException("Missing active network connection");
3626 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003627 int user = UserHandle.getUserId(Binder.getCallingUid());
3628 synchronized(mVpns) {
3629 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3630 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003631 }
3632
3633 /**
3634 * Return the information of the ongoing legacy VPN. This method is used
3635 * by VpnSettings and not available in ConnectivityManager. Permissions
3636 * are checked in Vpn class.
3637 * @hide
3638 */
3639 @Override
3640 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003641 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003642 int user = UserHandle.getUserId(Binder.getCallingUid());
3643 synchronized(mVpns) {
3644 return mVpns.get(user).getLegacyVpnInfo();
3645 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003646 }
3647
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003648 /**
Chad Brubaker94f3c8c2013-07-16 18:59:12 -07003649 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3650 * not available in ConnectivityManager.
3651 * Permissions are checked in Vpn class.
3652 * @hide
3653 */
3654 @Override
3655 public VpnConfig getVpnConfig() {
3656 int user = UserHandle.getUserId(Binder.getCallingUid());
3657 synchronized(mVpns) {
3658 return mVpns.get(user).getVpnConfig();
3659 }
3660 }
3661
3662 /**
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003663 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3664 * through NetworkStateTracker since it works differently. For example, it
3665 * needs to override DNS servers but never takes the default routes. It
3666 * relies on another data network, and it could keep existing connections
3667 * alive after reconnecting, switching between networks, or even resuming
3668 * from deep sleep. Calls from applications should be done synchronously
3669 * to avoid race conditions. As these are all hidden APIs, refactoring can
3670 * be done whenever a better abstraction is developed.
3671 */
3672 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003673 private VpnCallback() {
3674 }
3675
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003676 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003677 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003678 }
3679
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003680 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07003681 if (dnsServers == null) {
3682 restore();
3683 return;
3684 }
3685
3686 // Convert DNS servers into addresses.
3687 List<InetAddress> addresses = new ArrayList<InetAddress>();
3688 for (String address : dnsServers) {
3689 // Double check the addresses and remove invalid ones.
3690 try {
3691 addresses.add(InetAddress.parseNumericAddress(address));
3692 } catch (Exception e) {
3693 // ignore
3694 }
3695 }
3696 if (addresses.isEmpty()) {
3697 restore();
3698 return;
3699 }
3700
3701 // Concatenate search domains into a string.
3702 StringBuilder buffer = new StringBuilder();
3703 if (searchDomains != null) {
3704 for (String domain : searchDomains) {
3705 buffer.append(domain).append(' ');
3706 }
3707 }
3708 String domains = buffer.toString().trim();
3709
3710 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003711 synchronized (mDnsLock) {
Chad Brubaker73652d02013-07-23 17:13:36 -07003712 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003713 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003714
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003715 // Temporarily disable the default proxy (not global).
3716 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003717 mDefaultProxyDisabled = true;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003718 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003719 sendProxyBroadcast(null);
3720 }
3721 }
3722
3723 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003724 }
3725
Chia-chi Yehcc844502011-07-14 18:01:57 -07003726 public void restore() {
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003727 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003728 mDefaultProxyDisabled = false;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003729 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003730 sendProxyBroadcast(mDefaultProxy);
3731 }
3732 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003733 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003734
3735 public void protect(ParcelFileDescriptor socket) {
3736 try {
3737 final int mark = mNetd.getMarkForProtect();
3738 NetworkUtils.markSocket(socket.getFd(), mark);
3739 } catch (RemoteException e) {
3740 }
3741 }
3742
3743 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3744 for (RouteInfo route : routes) {
3745 try {
3746 mNetd.setMarkedForwardingRoute(interfaze, route);
3747 } catch (RemoteException e) {
3748 }
3749 }
3750 }
3751
3752 public void setMarkedForwarding(String interfaze) {
3753 try {
3754 mNetd.setMarkedForwarding(interfaze);
3755 } catch (RemoteException e) {
3756 }
3757 }
3758
3759 public void clearMarkedForwarding(String interfaze) {
3760 try {
3761 mNetd.clearMarkedForwarding(interfaze);
3762 } catch (RemoteException e) {
3763 }
3764 }
3765
3766 public void addUserForwarding(String interfaze, int uid) {
3767 int uidStart = uid * UserHandle.PER_USER_RANGE;
3768 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3769 addUidForwarding(interfaze, uidStart, uidEnd);
3770 }
3771
3772 public void clearUserForwarding(String interfaze, int uid) {
3773 int uidStart = uid * UserHandle.PER_USER_RANGE;
3774 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3775 clearUidForwarding(interfaze, uidStart, uidEnd);
3776 }
3777
3778 public void addUidForwarding(String interfaze, int uidStart, int uidEnd) {
3779 try {
3780 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
3781 mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
3782 } catch (RemoteException e) {
3783 }
3784
3785 }
3786
3787 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd) {
3788 try {
3789 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
3790 mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
3791 } catch (RemoteException e) {
3792 }
3793
3794 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003795 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003796
3797 @Override
3798 public boolean updateLockdownVpn() {
Jeff Sharkey760c6202013-01-31 17:22:26 -08003799 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3800 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3801 return false;
3802 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003803
3804 // Tear down existing lockdown if profile was removed
3805 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3806 if (mLockdownEnabled) {
Kenny Root0ded63c2013-02-14 10:18:38 -08003807 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003808 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3809 return false;
3810 }
3811
3812 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3813 final VpnProfile profile = VpnProfile.decode(
3814 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003815 int user = UserHandle.getUserId(Binder.getCallingUid());
3816 synchronized(mVpns) {
3817 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3818 profile));
3819 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003820 } else {
3821 setLockdownTracker(null);
3822 }
3823
3824 return true;
3825 }
3826
3827 /**
3828 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3829 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3830 */
3831 private void setLockdownTracker(LockdownVpnTracker tracker) {
3832 // Shutdown any existing tracker
3833 final LockdownVpnTracker existing = mLockdownTracker;
3834 mLockdownTracker = null;
3835 if (existing != null) {
3836 existing.shutdown();
3837 }
3838
3839 try {
3840 if (tracker != null) {
3841 mNetd.setFirewallEnabled(true);
Jeff Sharkeydb44d2c2013-02-28 16:57:58 -08003842 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003843 mLockdownTracker = tracker;
3844 mLockdownTracker.init();
3845 } else {
3846 mNetd.setFirewallEnabled(false);
3847 }
3848 } catch (RemoteException e) {
3849 // ignored; NMS lives inside system_server
3850 }
3851 }
3852
3853 private void throwIfLockdownEnabled() {
3854 if (mLockdownEnabled) {
3855 throw new IllegalStateException("Unavailable in lockdown mode");
3856 }
3857 }
Robert Greenwalt15a41532012-08-21 19:27:00 -07003858
3859 public void supplyMessenger(int networkType, Messenger messenger) {
3860 enforceConnectivityInternalPermission();
3861
3862 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3863 mNetTrackers[networkType].supplyMessenger(messenger);
3864 }
3865 }
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -07003866
3867 public int findConnectionTypeForIface(String iface) {
3868 enforceConnectivityInternalPermission();
3869
3870 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3871 for (NetworkStateTracker tracker : mNetTrackers) {
3872 if (tracker != null) {
3873 LinkProperties lp = tracker.getLinkProperties();
3874 if (lp != null && iface.equals(lp.getInterfaceName())) {
3875 return tracker.getNetworkInfo().getType();
3876 }
3877 }
3878 }
3879 return ConnectivityManager.TYPE_NONE;
3880 }
Wink Saville32506bc2013-06-29 21:10:57 -07003881
3882 /**
3883 * Have mobile data fail fast if enabled.
3884 *
3885 * @param enabled DctConstants.ENABLED/DISABLED
3886 */
3887 private void setEnableFailFastMobileData(int enabled) {
3888 int tag;
3889
3890 if (enabled == DctConstants.ENABLED) {
3891 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3892 } else {
3893 tag = mEnableFailFastMobileDataTag.get();
3894 }
3895 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3896 enabled));
3897 }
3898
Wink Savilled23fa092013-08-16 17:17:28 -07003899 private boolean isMobileDataStateTrackerReady() {
3900 MobileDataStateTracker mdst =
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003901 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savilled23fa092013-08-16 17:17:28 -07003902 return (mdst != null) && (mdst.isReady());
3903 }
3904
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003905 /**
3906 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3907 */
3908
3909 /**
3910 * No connection was possible to the network.
3911 */
3912 public static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
3913
3914 /**
3915 * A connection was made to the internet, all is well.
3916 */
3917 public static final int CMP_RESULT_CODE_CONNECTABLE = 1;
3918
3919 /**
3920 * A connection was made but there was a redirection, we appear to be in walled garden.
3921 * This is an indication of a warm sim on a mobile network.
3922 */
3923 public static final int CMP_RESULT_CODE_REDIRECTED = 2;
3924
3925 /**
3926 * A connection was made but no dns server was available to resolve a name to address.
3927 * This is an indication of a warm sim on a mobile network.
3928 */
3929 public static final int CMP_RESULT_CODE_NO_DNS = 3;
3930
3931 /**
3932 * A connection was made but could not open a TCP connection.
3933 * This is an indication of a warm sim on a mobile network.
3934 */
3935 public static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 4;
3936
3937 /**
3938 * The mobile network is a provisioning network.
3939 * This is an indication of a warm sim on a mobile network.
3940 */
3941 public static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
3942
3943 AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
3944
Wink Saville32506bc2013-06-29 21:10:57 -07003945 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003946 public int checkMobileProvisioning(int suggestedTimeOutMs) {
3947 int timeOutMs = -1;
3948 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
3949 enforceConnectivityInternalPermission();
Wink Savilled469c472013-07-02 10:55:14 -07003950
Wink Saville32506bc2013-06-29 21:10:57 -07003951 final long token = Binder.clearCallingIdentity();
3952 try {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003953 timeOutMs = suggestedTimeOutMs;
3954 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3955 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3956 }
3957
3958 // Check that mobile networks are supported
3959 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3960 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3961 if (DBG) log("checkMobileProvisioning: X no mobile network");
3962 return timeOutMs;
3963 }
3964
3965 // If we're already checking don't do it again
3966 // TODO: Add a queue of results...
3967 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
3968 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
3969 return timeOutMs;
3970 }
3971
3972 // Start off with notification off
3973 setProvNotificationVisible(false, ConnectivityManager.TYPE_NONE, null, null);
3974
3975 // See if we've alreadying determined if we've got a provsioning connection
3976 // if so we don't need to do anything active
3977 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
3978 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3979 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
3980
3981 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
3982 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
3983 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
3984
3985 if (isDefaultProvisioning || isHipriProvisioning) {
3986 if (mIsNotificationVisible) {
3987 if (DBG) {
3988 log("checkMobileProvisioning: provisioning-ignore notification is visible");
3989 }
3990 } else {
3991 NetworkInfo ni = null;
3992 if (isDefaultProvisioning) {
3993 ni = mdstDefault.getNetworkInfo();
3994 }
3995 if (isHipriProvisioning) {
3996 ni = mdstHipri.getNetworkInfo();
3997 }
3998 String url = getMobileProvisioningUrl();
3999 if ((ni != null) && (!TextUtils.isEmpty(url))) {
4000 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(), url);
4001 } else {
4002 if (DBG) log("checkMobileProvisioning: provisioning but no url, ignore");
4003 }
4004 }
4005 mIsCheckingMobileProvisioning.set(false);
4006 return timeOutMs;
4007 }
4008
Wink Saville32506bc2013-06-29 21:10:57 -07004009 CheckMp checkMp = new CheckMp(mContext, this);
4010 CheckMp.CallBack cb = new CheckMp.CallBack() {
4011 @Override
4012 void onComplete(Integer result) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004013 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Saville32506bc2013-06-29 21:10:57 -07004014 NetworkInfo ni =
4015 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4016 switch(result) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004017 case CMP_RESULT_CODE_CONNECTABLE:
4018 case CMP_RESULT_CODE_NO_CONNECTION: {
4019 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Saville32506bc2013-06-29 21:10:57 -07004020 break;
4021 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004022 case CMP_RESULT_CODE_REDIRECTED: {
4023 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalt39d56012013-07-16 12:06:09 -07004024 String url = getMobileProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004025 if (TextUtils.isEmpty(url)) {
Robert Greenwalt39d56012013-07-16 12:06:09 -07004026 url = getMobileRedirectedProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004027 }
4028 if (TextUtils.isEmpty(url) == false) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004029 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
4030 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(),
4031 url);
Wink Saville32506bc2013-06-29 21:10:57 -07004032 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004033 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Saville32506bc2013-06-29 21:10:57 -07004034 }
4035 break;
4036 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004037 case CMP_RESULT_CODE_NO_DNS:
4038 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Robert Greenwalt39d56012013-07-16 12:06:09 -07004039 String url = getMobileProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004040 if (TextUtils.isEmpty(url) == false) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004041 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
4042 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(),
4043 url);
Wink Saville32506bc2013-06-29 21:10:57 -07004044 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004045 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Saville32506bc2013-06-29 21:10:57 -07004046 }
4047 break;
4048 }
4049 default: {
4050 loge("CheckMp.onComplete: ignore unexpected result=" + result);
4051 break;
4052 }
4053 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004054 mIsCheckingMobileProvisioning.set(false);
Wink Saville32506bc2013-06-29 21:10:57 -07004055 }
4056 };
4057 CheckMp.Params params =
4058 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004059 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Saville32506bc2013-06-29 21:10:57 -07004060 checkMp.execute(params);
4061 } finally {
4062 Binder.restoreCallingIdentity(token);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004063 if (DBG) log("checkMobileProvisioning: X");
Wink Saville32506bc2013-06-29 21:10:57 -07004064 }
4065 return timeOutMs;
4066 }
4067
4068 static class CheckMp extends
4069 AsyncTask<CheckMp.Params, Void, Integer> {
4070 private static final String CHECKMP_TAG = "CheckMp";
4071 public static final int MAX_TIMEOUT_MS = 60000;
4072 private static final int SOCKET_TIMEOUT_MS = 5000;
4073 private Context mContext;
4074 private ConnectivityService mCs;
4075 private TelephonyManager mTm;
4076 private Params mParams;
4077
4078 /**
4079 * Parameters for AsyncTask.execute
4080 */
4081 static class Params {
4082 private String mUrl;
4083 private long mTimeOutMs;
4084 private CallBack mCb;
4085
4086 Params(String url, long timeOutMs, CallBack cb) {
4087 mUrl = url;
4088 mTimeOutMs = timeOutMs;
4089 mCb = cb;
4090 }
4091
4092 @Override
4093 public String toString() {
4094 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4095 }
4096 }
4097
4098 /**
4099 * The call back object passed in Params. onComplete will be called
4100 * on the main thread.
4101 */
4102 abstract static class CallBack {
4103 // Called on the main thread.
4104 abstract void onComplete(Integer result);
4105 }
4106
4107 public CheckMp(Context context, ConnectivityService cs) {
4108 mContext = context;
4109 mCs = cs;
4110
4111 // Setup access to TelephonyService we'll be using.
4112 mTm = (TelephonyManager) mContext.getSystemService(
4113 Context.TELEPHONY_SERVICE);
4114 }
4115
4116 /**
4117 * Get the default url to use for the test.
4118 */
4119 public String getDefaultUrl() {
4120 // See http://go/clientsdns for usage approval
4121 String server = Settings.Global.getString(mContext.getContentResolver(),
4122 Settings.Global.CAPTIVE_PORTAL_SERVER);
4123 if (server == null) {
4124 server = "clients3.google.com";
4125 }
4126 return "http://" + server + "/generate_204";
4127 }
4128
4129 /**
4130 * Detect if its possible to connect to the http url. DNS based detection techniques
4131 * do not work at all hotspots. The best way to check is to perform a request to
4132 * a known address that fetches the data we expect.
4133 */
4134 private synchronized Integer isMobileOk(Params params) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004135 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004136 Uri orgUri = Uri.parse(params.mUrl);
4137 Random rand = new Random();
4138 mParams = params;
4139
Wink Saville69e2de02013-08-13 12:41:06 -07004140 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
4141 log("isMobileOk: not mobile capable");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004142 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville69e2de02013-08-13 12:41:06 -07004143 return result;
4144 }
Wink Saville32506bc2013-06-29 21:10:57 -07004145
Wink Saville69e2de02013-08-13 12:41:06 -07004146 try {
Wink Saville32506bc2013-06-29 21:10:57 -07004147 // Continue trying to connect until time has run out
4148 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville15f12922013-08-07 11:02:57 -07004149
Wink Savilled23fa092013-08-16 17:17:28 -07004150 if (!mCs.isMobileDataStateTrackerReady()) {
4151 // Wait for MobileDataStateTracker to be ready.
4152 if (DBG) log("isMobileOk: mdst is not ready");
4153 while(SystemClock.elapsedRealtime() < endTime) {
4154 if (mCs.isMobileDataStateTrackerReady()) {
4155 // Enable fail fast as we'll do retries here and use a
4156 // hipri connection so the default connection stays active.
4157 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4158 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4159 break;
4160 }
4161 sleep(1);
4162 }
4163 }
4164
4165 log("isMobileOk: start hipri url=" + params.mUrl);
4166
Wink Saville15f12922013-08-07 11:02:57 -07004167 // First wait until we can start using hipri
4168 Binder binder = new Binder();
4169 while(SystemClock.elapsedRealtime() < endTime) {
4170 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4171 Phone.FEATURE_ENABLE_HIPRI, binder);
4172 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4173 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4174 log("isMobileOk: hipri started");
4175 break;
4176 }
4177 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004178 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville15f12922013-08-07 11:02:57 -07004179 sleep(1);
4180 }
4181
4182 // Continue trying to connect until time has run out
Wink Saville32506bc2013-06-29 21:10:57 -07004183 while(SystemClock.elapsedRealtime() < endTime) {
4184 try {
4185 // Wait for hipri to connect.
4186 // TODO: Don't poll and handle situation where hipri fails
4187 // because default is retrying. See b/9569540
4188 NetworkInfo.State state = mCs
4189 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4190 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004191 if (true/*VDBG*/) {
Wink Savilled28eef42013-07-31 15:49:04 -07004192 log("isMobileOk: not connected ni=" +
Wink Saville32506bc2013-06-29 21:10:57 -07004193 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Savilled28eef42013-07-31 15:49:04 -07004194 }
Wink Saville32506bc2013-06-29 21:10:57 -07004195 sleep(1);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004196 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004197 continue;
4198 }
4199
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004200 // Hipri has started check if this is a provisioning url
4201 MobileDataStateTracker mdst = (MobileDataStateTracker)
4202 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4203 if (mdst.isProvisioningNetwork()) {
4204 if (DBG) log("isMobileOk: isProvisioningNetwork is true, no TCP conn");
4205 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
4206 return result;
4207 } else {
4208 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4209 }
4210
Wink Saville32506bc2013-06-29 21:10:57 -07004211 // Get of the addresses associated with the url host. We need to use the
4212 // address otherwise HttpURLConnection object will use the name to get
4213 // the addresses and is will try every address but that will bypass the
4214 // route to host we setup and the connection could succeed as the default
4215 // interface might be connected to the internet via wifi or other interface.
4216 InetAddress[] addresses;
4217 try {
4218 addresses = InetAddress.getAllByName(orgUri.getHost());
4219 } catch (UnknownHostException e) {
4220 log("isMobileOk: UnknownHostException");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004221 result = CMP_RESULT_CODE_NO_DNS;
Wink Saville32506bc2013-06-29 21:10:57 -07004222 return result;
4223 }
4224 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4225
4226 // Get the type of addresses supported by this link
4227 LinkProperties lp = mCs.getLinkProperties(
4228 ConnectivityManager.TYPE_MOBILE_HIPRI);
Lorenzo Colitti09de4182013-08-08 11:00:12 +09004229 boolean linkHasIpv4 = lp.hasIPv4Address();
4230 boolean linkHasIpv6 = lp.hasIPv6Address();
Wink Saville32506bc2013-06-29 21:10:57 -07004231 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4232 + " linkHasIpv6=" + linkHasIpv6);
4233
4234 // Loop through at most 3 valid addresses or all of the address or until
4235 // we run out of time
4236 int loops = Math.min(3, addresses.length);
4237 for(int validAddr=0, addrTried=0;
4238 (validAddr < loops) && (addrTried < addresses.length)
4239 && (SystemClock.elapsedRealtime() < endTime);
4240 addrTried ++) {
4241
4242 // Choose the address at random but make sure its type is supported
4243 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
4244 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
4245 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
4246 // Valid address, so use it
4247 validAddr += 1;
4248 } else {
4249 // Invalid address so try next address
4250 continue;
4251 }
4252
4253 // Make a route to host so we check the specific interface.
4254 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4255 hostAddr.getAddress())) {
4256 // Wait a short time to be sure the route is established ??
4257 log("isMobileOk:"
4258 + " wait to establish route to hostAddr=" + hostAddr);
4259 sleep(3);
4260 } else {
4261 log("isMobileOk:"
4262 + " could not establish route to hostAddr=" + hostAddr);
4263 continue;
4264 }
4265
4266 // Rewrite the url to have numeric address to use the specific route.
4267 // I also set the "Connection" to "Close" as by default "Keep-Alive"
4268 // is used which is useless in this case.
4269 URL newUrl = new URL(orgUri.getScheme() + "://"
4270 + hostAddr.getHostAddress() + orgUri.getPath());
4271 log("isMobileOk: newUrl=" + newUrl);
4272
4273 HttpURLConnection urlConn = null;
4274 try {
4275 // Open the connection set the request header and get the response
4276 urlConn = (HttpURLConnection) newUrl.openConnection(
4277 java.net.Proxy.NO_PROXY);
4278 urlConn.setInstanceFollowRedirects(false);
4279 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4280 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4281 urlConn.setUseCaches(false);
4282 urlConn.setAllowUserInteraction(false);
4283 urlConn.setRequestProperty("Connection", "close");
4284 int responseCode = urlConn.getResponseCode();
4285 if (responseCode == 204) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004286 result = CMP_RESULT_CODE_CONNECTABLE;
Wink Saville32506bc2013-06-29 21:10:57 -07004287 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004288 result = CMP_RESULT_CODE_REDIRECTED;
Wink Saville32506bc2013-06-29 21:10:57 -07004289 }
4290 log("isMobileOk: connected responseCode=" + responseCode);
4291 urlConn.disconnect();
4292 urlConn = null;
4293 return result;
4294 } catch (Exception e) {
4295 log("isMobileOk: HttpURLConnection Exception e=" + e);
4296 if (urlConn != null) {
4297 urlConn.disconnect();
4298 urlConn = null;
4299 }
4300 }
4301 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004302 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004303 log("isMobileOk: loops|timed out");
4304 return result;
4305 } catch (Exception e) {
4306 log("isMobileOk: Exception e=" + e);
4307 continue;
4308 }
4309 }
4310 log("isMobileOk: timed out");
4311 } finally {
4312 log("isMobileOk: F stop hipri");
4313 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4314 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4315 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004316
4317 // Wait for hipri to disconnect.
4318 long endTime = SystemClock.elapsedRealtime() + 5000;
4319
4320 while(SystemClock.elapsedRealtime() < endTime) {
4321 NetworkInfo.State state = mCs
4322 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4323 if (state != NetworkInfo.State.DISCONNECTED) {
4324 if (VDBG) {
4325 log("isMobileOk: connected ni=" +
4326 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4327 }
4328 sleep(1);
4329 continue;
4330 }
4331 }
4332
Wink Saville32506bc2013-06-29 21:10:57 -07004333 log("isMobileOk: X result=" + result);
4334 }
4335 return result;
4336 }
4337
4338 @Override
4339 protected Integer doInBackground(Params... params) {
4340 return isMobileOk(params[0]);
4341 }
4342
4343 @Override
4344 protected void onPostExecute(Integer result) {
4345 log("onPostExecute: result=" + result);
4346 if ((mParams != null) && (mParams.mCb != null)) {
4347 mParams.mCb.onComplete(result);
4348 }
4349 }
4350
4351 private String inetAddressesToString(InetAddress[] addresses) {
4352 StringBuffer sb = new StringBuffer();
4353 boolean firstTime = true;
4354 for(InetAddress addr : addresses) {
4355 if (firstTime) {
4356 firstTime = false;
4357 } else {
4358 sb.append(",");
4359 }
4360 sb.append(addr);
4361 }
4362 return sb.toString();
4363 }
4364
4365 private void printNetworkInfo() {
4366 boolean hasIccCard = mTm.hasIccCard();
4367 int simState = mTm.getSimState();
4368 log("hasIccCard=" + hasIccCard
4369 + " simState=" + simState);
4370 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4371 if (ni != null) {
4372 log("ni.length=" + ni.length);
4373 for (NetworkInfo netInfo: ni) {
4374 log("netInfo=" + netInfo.toString());
4375 }
4376 } else {
4377 log("no network info ni=null");
4378 }
4379 }
4380
4381 /**
4382 * Sleep for a few seconds then return.
4383 * @param seconds
4384 */
4385 private static void sleep(int seconds) {
4386 try {
4387 Thread.sleep(seconds * 1000);
4388 } catch (InterruptedException e) {
4389 e.printStackTrace();
4390 }
4391 }
4392
Wink Saville32506bc2013-06-29 21:10:57 -07004393 private void log(String s) {
4394 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4395 }
4396 }
4397
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004398 // TODO: Move to ConnectivityManager and make public?
4399 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4400 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Saville32506bc2013-06-29 21:10:57 -07004401
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004402 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4403 @Override
4404 public void onReceive(Context context, Intent intent) {
4405 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4406 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4407 }
4408 }
4409 };
4410
4411 private void handleMobileProvisioningAction(String url) {
4412 // Notication mark notification as not visible
4413 setProvNotificationVisible(false, ConnectivityManager.TYPE_NONE, null, null);
4414
4415 // If provisioning network handle as a special case,
4416 // otherwise launch browser with the intent directly.
4417 NetworkInfo ni = getProvisioningNetworkInfo();
Wink Savilleb1a32022013-09-05 12:02:25 -07004418 if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004419 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4420 MobileDataStateTracker mdst = (MobileDataStateTracker)
4421 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4422 mdst.enableMobileProvisioning(url);
4423 } else {
4424 if (DBG) log("handleMobileProvisioningAction: on default network");
4425 Intent newIntent =
4426 new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4427 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4428 Intent.FLAG_ACTIVITY_NEW_TASK);
4429 try {
4430 mContext.startActivity(newIntent);
4431 } catch (ActivityNotFoundException e) {
4432 loge("handleMobileProvisioningAction: startActivity failed" + e);
4433 }
4434 }
4435 }
4436
4437 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4438 private volatile boolean mIsNotificationVisible = false;
4439
4440 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4441 String url) {
4442 if (DBG) {
4443 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4444 + " extraInfo=" + extraInfo + " url=" + url);
4445 }
Wink Saville32506bc2013-06-29 21:10:57 -07004446
4447 Resources r = Resources.getSystem();
4448 NotificationManager notificationManager = (NotificationManager) mContext
4449 .getSystemService(Context.NOTIFICATION_SERVICE);
4450
4451 if (visible) {
4452 CharSequence title;
4453 CharSequence details;
4454 int icon;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004455 Intent intent;
4456 Notification notification = new Notification();
4457 switch (networkType) {
Wink Saville32506bc2013-06-29 21:10:57 -07004458 case ConnectivityManager.TYPE_WIFI:
Wink Saville32506bc2013-06-29 21:10:57 -07004459 title = r.getString(R.string.wifi_available_sign_in, 0);
4460 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004461 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004462 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004463 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4464 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4465 Intent.FLAG_ACTIVITY_NEW_TASK);
4466 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004467 break;
4468 case ConnectivityManager.TYPE_MOBILE:
4469 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Saville32506bc2013-06-29 21:10:57 -07004470 title = r.getString(R.string.network_available_sign_in, 0);
4471 // TODO: Change this to pull from NetworkInfo once a printable
4472 // name has been added to it
4473 details = mTelephonyManager.getNetworkOperatorName();
4474 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004475 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4476 intent.putExtra("EXTRA_URL", url);
4477 intent.setFlags(0);
4478 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004479 break;
4480 default:
Wink Saville32506bc2013-06-29 21:10:57 -07004481 title = r.getString(R.string.network_available_sign_in, 0);
4482 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004483 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004484 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004485 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4486 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4487 Intent.FLAG_ACTIVITY_NEW_TASK);
4488 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004489 break;
4490 }
4491
Wink Saville32506bc2013-06-29 21:10:57 -07004492 notification.when = 0;
4493 notification.icon = icon;
4494 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Saville32506bc2013-06-29 21:10:57 -07004495 notification.tickerText = title;
4496 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4497
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004498 try {
4499 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4500 } catch (NullPointerException npe) {
4501 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4502 npe.printStackTrace();
4503 }
Wink Saville32506bc2013-06-29 21:10:57 -07004504 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004505 try {
4506 notificationManager.cancel(NOTIFICATION_ID, 1);
4507 } catch (NullPointerException npe) {
4508 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4509 npe.printStackTrace();
4510 }
Wink Saville32506bc2013-06-29 21:10:57 -07004511 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004512 mIsNotificationVisible = visible;
Wink Saville32506bc2013-06-29 21:10:57 -07004513 }
4514
Robert Greenwalt39d56012013-07-16 12:06:09 -07004515 /** Location to an updatable file listing carrier provisioning urls.
4516 * An example:
4517 *
4518 * <?xml version="1.0" encoding="utf-8"?>
4519 * <provisioningUrls>
4520 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4521 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4522 * </provisioningUrls>
4523 */
4524 private static final String PROVISIONING_URL_PATH =
4525 "/data/misc/radio/provisioning_urls.xml";
4526 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville32506bc2013-06-29 21:10:57 -07004527
Robert Greenwalt39d56012013-07-16 12:06:09 -07004528 /** XML tag for root element. */
4529 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4530 /** XML tag for individual url */
4531 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4532 /** XML tag for redirected url */
4533 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4534 /** XML attribute for mcc */
4535 private static final String ATTR_MCC = "mcc";
4536 /** XML attribute for mnc */
4537 private static final String ATTR_MNC = "mnc";
4538
4539 private static final int REDIRECTED_PROVISIONING = 1;
4540 private static final int PROVISIONING = 2;
4541
4542 private String getProvisioningUrlBaseFromFile(int type) {
4543 FileReader fileReader = null;
4544 XmlPullParser parser = null;
4545 Configuration config = mContext.getResources().getConfiguration();
4546 String tagType;
4547
4548 switch (type) {
4549 case PROVISIONING:
4550 tagType = TAG_PROVISIONING_URL;
4551 break;
4552 case REDIRECTED_PROVISIONING:
4553 tagType = TAG_REDIRECTED_URL;
4554 break;
4555 default:
4556 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4557 type);
4558 }
4559
4560 try {
4561 fileReader = new FileReader(mProvisioningUrlFile);
4562 parser = Xml.newPullParser();
4563 parser.setInput(fileReader);
4564 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4565
4566 while (true) {
4567 XmlUtils.nextElement(parser);
4568
4569 String element = parser.getName();
4570 if (element == null) break;
4571
4572 if (element.equals(tagType)) {
4573 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4574 try {
4575 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4576 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4577 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4578 parser.next();
4579 if (parser.getEventType() == XmlPullParser.TEXT) {
4580 return parser.getText();
4581 }
4582 }
4583 }
4584 } catch (NumberFormatException e) {
4585 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4586 }
4587 }
4588 }
4589 return null;
4590 } catch (FileNotFoundException e) {
4591 loge("Carrier Provisioning Urls file not found");
4592 } catch (XmlPullParserException e) {
4593 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4594 } catch (IOException e) {
4595 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4596 } finally {
4597 if (fileReader != null) {
4598 try {
4599 fileReader.close();
4600 } catch (IOException e) {}
4601 }
4602 }
4603 return null;
4604 }
4605
Wink Saville8432cf42013-07-20 20:31:59 -07004606 @Override
4607 public String getMobileRedirectedProvisioningUrl() {
4608 enforceConnectivityInternalPermission();
Robert Greenwalt39d56012013-07-16 12:06:09 -07004609 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4610 if (TextUtils.isEmpty(url)) {
4611 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4612 }
4613 return url;
4614 }
4615
Wink Saville8432cf42013-07-20 20:31:59 -07004616 @Override
Robert Greenwalt39d56012013-07-16 12:06:09 -07004617 public String getMobileProvisioningUrl() {
4618 enforceConnectivityInternalPermission();
4619 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4620 if (TextUtils.isEmpty(url)) {
4621 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville8432cf42013-07-20 20:31:59 -07004622 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004623 } else {
Wink Saville8432cf42013-07-20 20:31:59 -07004624 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004625 }
Wink Savillec118d7e2013-07-10 23:00:07 -07004626 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville32506bc2013-06-29 21:10:57 -07004627 if (!TextUtils.isEmpty(url)) {
Wink Savillec118d7e2013-07-10 23:00:07 -07004628 String phoneNumber = mTelephonyManager.getLine1Number();
4629 if (TextUtils.isEmpty(phoneNumber)) {
4630 phoneNumber = "0000000000";
4631 }
Wink Saville32506bc2013-06-29 21:10:57 -07004632 url = String.format(url,
4633 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4634 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savillec118d7e2013-07-10 23:00:07 -07004635 phoneNumber /* Phone numer */);
Wink Saville32506bc2013-06-29 21:10:57 -07004636 }
4637
Wink Saville32506bc2013-06-29 21:10:57 -07004638 return url;
4639 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07004640
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004641 @Override
4642 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4643 String extraInfo, String url) {
4644 enforceConnectivityInternalPermission();
4645 setProvNotificationVisible(visible, networkType, extraInfo, url);
4646 }
Wink Savillecb117d32013-08-29 14:57:08 -07004647
Chad Brubakerb7652cd2013-06-14 11:16:51 -07004648 private void onUserStart(int userId) {
4649 synchronized(mVpns) {
4650 Vpn userVpn = mVpns.get(userId);
4651 if (userVpn != null) {
4652 loge("Starting user already has a VPN");
4653 return;
4654 }
4655 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4656 mVpns.put(userId, userVpn);
4657 userVpn.startMonitoring(mContext, mTrackerHandler);
4658 }
4659 }
4660
4661 private void onUserStop(int userId) {
4662 synchronized(mVpns) {
4663 Vpn userVpn = mVpns.get(userId);
4664 if (userVpn == null) {
4665 loge("Stopping user has no VPN");
4666 return;
4667 }
4668 mVpns.delete(userId);
4669 }
4670 }
4671
4672 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4673 @Override
4674 public void onReceive(Context context, Intent intent) {
4675 final String action = intent.getAction();
4676 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4677 if (userId == UserHandle.USER_NULL) return;
4678
4679 if (Intent.ACTION_USER_STARTING.equals(action)) {
4680 onUserStart(userId);
4681 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4682 onUserStop(userId);
4683 }
4684 }
4685 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004686
4687 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004688 public LinkQualityInfo getLinkQualityInfo(int networkType) {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004689 enforceAccessPermission();
4690 if (isNetworkTypeValid(networkType)) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004691 return mNetTrackers[networkType].getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004692 } else {
4693 return null;
4694 }
4695 }
4696
4697 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004698 public LinkQualityInfo getActiveLinkQualityInfo() {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004699 enforceAccessPermission();
4700 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004701 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004702 } else {
4703 return null;
4704 }
4705 }
4706
4707 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004708 public LinkQualityInfo[] getAllLinkQualityInfo() {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004709 enforceAccessPermission();
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004710 final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004711 for (NetworkStateTracker tracker : mNetTrackers) {
4712 if (tracker != null) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004713 LinkQualityInfo li = tracker.getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004714 if (li != null) {
4715 result.add(li);
4716 }
4717 }
4718 }
4719
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004720 return result.toArray(new LinkQualityInfo[result.size()]);
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004721 }
4722
4723 /* Infrastructure for network sampling */
4724
4725 private void handleNetworkSamplingTimeout() {
4726
4727 log("Sampling interval elapsed, updating statistics ..");
4728
4729 // initialize list of interfaces ..
4730 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4731 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4732 for (NetworkStateTracker tracker : mNetTrackers) {
4733 if (tracker != null) {
4734 String ifaceName = tracker.getNetworkInterfaceName();
4735 if (ifaceName != null) {
4736 mapIfaceToSample.put(ifaceName, null);
4737 }
4738 }
4739 }
4740
4741 // Read samples for all interfaces
4742 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4743
4744 // process samples for all networks
4745 for (NetworkStateTracker tracker : mNetTrackers) {
4746 if (tracker != null) {
4747 String ifaceName = tracker.getNetworkInterfaceName();
4748 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4749 if (ss != null) {
4750 // end the previous sampling cycle
4751 tracker.stopSampling(ss);
4752 // start a new sampling cycle ..
4753 tracker.startSampling(ss);
4754 }
4755 }
4756 }
4757
4758 log("Done.");
4759
4760 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4761 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4762 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4763
4764 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4765
4766 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
4767 }
4768
4769 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
4770 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
4771 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
4772 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004773}
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004774