blob: 5695ee510d1b00faead160b44321fe6a92e8cc2a [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;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Jeff Sharkey168cd722013-09-10 21:03:27 -070062import android.net.LinkQualityInfo;
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;
The Android Open Source Project28527d22009-03-03 19:31:44 -080092import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070093import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080094import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -070095import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080096import android.provider.Settings;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070097import android.security.Credentials;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -070098import android.security.KeyStore;
Wink Saville32506bc2013-06-29 21:10:57 -070099import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700100import android.text.TextUtils;
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800101import android.util.Slog;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700102import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700103import android.util.SparseIntArray;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700104import android.util.Xml;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800105
Wink Saville32506bc2013-06-29 21:10:57 -0700106import com.android.internal.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400107import com.android.internal.annotations.GuardedBy;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700108import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700109import com.android.internal.net.VpnConfig;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700110import com.android.internal.net.VpnProfile;
Wink Saville32506bc2013-06-29 21:10:57 -0700111import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700112import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700113import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700114import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700115import com.android.internal.util.XmlUtils;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700116import com.android.server.am.BatteryStatsService;
John Spurlock1f5cec72013-06-24 14:20:23 -0400117import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900118import com.android.server.connectivity.Nat464Xlat;
Jason Monka5bf2842013-07-03 17:04:33 -0400119import com.android.server.connectivity.PacManager;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800120import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700121import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700122import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700123import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700124import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700125import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700126
tk.mun093f55c2011-10-13 22:51:57 +0900127import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700128
Robert Greenwalt39d56012013-07-16 12:06:09 -0700129import org.xmlpull.v1.XmlPullParser;
130import org.xmlpull.v1.XmlPullParserException;
131
132import java.io.File;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800133import java.io.FileDescriptor;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700134import java.io.FileNotFoundException;
135import java.io.FileReader;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700136import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800137import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900138import java.lang.reflect.Constructor;
Wink Saville32506bc2013-06-29 21:10:57 -0700139import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700140import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700141import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700142import java.net.InetAddress;
Wink Saville32506bc2013-06-29 21:10:57 -0700143import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700144import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700145import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700146import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700147import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700148import java.util.GregorianCalendar;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700149import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700150import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700151import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700152import java.util.Map;
Wink Saville32506bc2013-06-29 21:10:57 -0700153import java.util.Random;
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700154import java.util.concurrent.atomic.AtomicBoolean;
Wink Saville32506bc2013-06-29 21:10:57 -0700155import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156
157/**
158 * @hide
159 */
160public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700161 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800162
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700163 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700164 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800165
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700166 private static final boolean LOGD_RULES = false;
167
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700168 // TODO: create better separation between radio types and network types
169
Robert Greenwalt2034b912009-08-12 16:08:25 -0700170 // how long to wait before switching back to a radio's default network
171 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
172 // system property that can override the above value
173 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
174 "android.telephony.apn-restore";
175
Wink Saville32506bc2013-06-29 21:10:57 -0700176 // Default value if FAIL_FAST_TIME_MS is not set
177 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
178 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
179 private static final String FAIL_FAST_TIME_MS =
180 "persist.radio.fail_fast_time_ms";
181
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700182 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
183 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
184
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -0700185 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700186
187 private PendingIntent mSampleIntervalElapsedIntent;
188
189 // Set network sampling interval at 12 minutes, this way, even if the timers get
190 // aggregated, it will fire at around 15 minutes, which should allow us to
191 // aggregate this timer with other timers (specially the socket keep alive timers)
192 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
193
194 // start network sampling a minute after booting ...
195 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
196
197 AlarmManager mAlarmManager;
198
Robert Greenwaltbd492212011-05-06 17:10:53 -0700199 // used in recursive route setting to add gateways for the host for which
200 // a host route was requested.
201 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
202
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800203 private Tethering mTethering;
204
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700205 private KeyStore mKeyStore;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700206
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700207 @GuardedBy("mVpns")
208 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700209 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700210
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700211 private boolean mLockdownEnabled;
212 private LockdownVpnTracker mLockdownTracker;
213
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900214 private Nat464Xlat mClat;
215
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700216 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
217 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700218 /** Currently active network rules by UID. */
219 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700220 /** Set of ifaces that are costly. */
221 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700222
The Android Open Source Project28527d22009-03-03 19:31:44 -0800223 /**
224 * Sometimes we want to refer to the individual network state
225 * trackers separately, and sometimes we just want to treat them
226 * abstractly.
227 */
228 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700229
Irfan Sheriff0ad0d132012-08-16 12:49:23 -0700230 /* Handles captive portal check on a network */
231 private CaptivePortalTracker mCaptivePortalTracker;
232
Robert Greenwalt2034b912009-08-12 16:08:25 -0700233 /**
Wink Saville051a6642011-07-13 13:44:13 -0700234 * The link properties that define the current links
235 */
236 private LinkProperties mCurrentLinkProperties[];
237
238 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700239 * A per Net list of the PID's that requested access to the net
240 * used both as a refcount and for per-PID DNS selection
241 */
Mattias Falkd697aa22011-08-23 14:15:13 +0200242 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700243
Robert Greenwalt2034b912009-08-12 16:08:25 -0700244 // priority order of the nettrackers
245 // (excluding dynamically set mNetworkPreference)
246 // TODO - move mNetworkTypePreference into this
247 private int[] mPriorityList;
248
The Android Open Source Project28527d22009-03-03 19:31:44 -0800249 private Context mContext;
250 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700251 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700252 // 0 is full bad, 100 is full good
Wink Saville151eaa62013-01-31 00:30:13 +0000253 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700254 private int mDefaultInetConditionPublished = 0;
255 private boolean mInetConditionChangeInFlight = false;
256 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800257
Chia-chi Yehcc844502011-07-14 18:01:57 -0700258 private Object mDnsLock = new Object();
Robert Greenwalte41e3b32013-02-11 15:25:10 -0800259 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800260
261 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700262 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800263
Robert Greenwalt355205c2011-05-10 15:05:02 -0700264 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700265 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700266
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700267 private static final int ENABLED = 1;
268 private static final int DISABLED = 0;
269
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700270 private static final boolean ADD = true;
271 private static final boolean REMOVE = false;
272
273 private static final boolean TO_DEFAULT_TABLE = true;
274 private static final boolean TO_SECONDARY_TABLE = false;
275
Chad Brubaker49db4222013-07-15 16:34:04 -0700276 private static final boolean EXEMPT = true;
277 private static final boolean UNEXEMPT = false;
278
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700279 /**
280 * used internally as a delayed event to make us switch back to the
281 * default network
282 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700283 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700284
285 /**
286 * used internally to change our mobile data enabled flag
287 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700288 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700289
290 /**
291 * used internally to change our network preference setting
292 * arg1 = networkType to prefer
293 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700294 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700295
296 /**
297 * used internally to synchronize inet condition reports
298 * arg1 = networkType
299 * arg2 = condition (0 bad, 100 good)
300 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700301 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700302
303 /**
304 * used internally to mark the end of inet condition hold periods
305 * arg1 = networkType
306 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700307 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700308
309 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700310 * used internally to set enable/disable cellular data
311 * arg1 = ENBALED or DISABLED
312 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700313 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700314
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700315 /**
316 * used internally to clear a wakelock when transitioning
317 * from one net to another
318 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700319 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700320
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700321 /**
322 * used internally to reload global proxy settings
323 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700324 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700325
Robert Greenwalt34848c02011-03-25 13:09:25 -0700326 /**
327 * used internally to set external dependency met/unmet
328 * arg1 = ENABLED (met) or DISABLED (unmet)
329 * arg2 = NetworkType
330 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700331 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700332
Chia-chi Yehcc844502011-07-14 18:01:57 -0700333 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700334 * used internally to send a sticky broadcast delayed.
335 */
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700336 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700337
Jeff Sharkey805662d2011-08-19 02:24:24 -0700338 /**
339 * Used internally to
340 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
341 */
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700342 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700343
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700344 private static final int EVENT_VPN_STATE_CHANGED = 13;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700345
Wink Saville32506bc2013-06-29 21:10:57 -0700346 /**
347 * Used internally to disable fail fast of mobile data
348 */
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700349 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Saville32506bc2013-06-29 21:10:57 -0700350
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700351 /**
352 * user internally to indicate that data sampling interval is up
353 */
354 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
355
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700356 /** Handler used for internal events. */
357 private InternalHandler mHandler;
358 /** Handler used for incoming {@link NetworkStateTracker} events. */
359 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700360
361 // list of DeathRecipients used to make sure features are turned off when
362 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500363 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700364
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400365 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800366 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400367
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700368 private PowerManager.WakeLock mNetTransitionWakeLock;
369 private String mNetTransitionWakeLockCausedBy = "";
370 private int mNetTransitionWakeLockSerialNumber;
371 private int mNetTransitionWakeLockTimeout;
372
Robert Greenwalt94daa182010-09-01 11:34:05 -0700373 private InetAddress mDefaultDns;
374
Chad Brubaker49db4222013-07-15 16:34:04 -0700375 // Lock for protecting access to mAddedRoutes and mExemptAddresses
376 private final Object mRoutesLock = new Object();
377
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700378 // this collection is used to refcount the added routes - if there are none left
379 // it's time to remove the route from the route table
Chad Brubaker49db4222013-07-15 16:34:04 -0700380 @GuardedBy("mRoutesLock")
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700381 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
382
Chad Brubaker49db4222013-07-15 16:34:04 -0700383 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
384 // used to handle cleanup of exempt rules
385 @GuardedBy("mRoutesLock")
386 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
387
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700388 // used in DBG mode to track inet condition reports
389 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
390 private ArrayList mInetLog;
391
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700392 // track the current default http proxy - tell the world if we get a new one (real change)
393 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltf9661d32013-04-05 17:14:19 -0700394 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700395 private boolean mDefaultProxyDisabled = false;
396
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700397 // track the global proxy.
398 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700399
Jason Monka5bf2842013-07-03 17:04:33 -0400400 private PacManager mPacManager = null;
401
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700402 private SettingsObserver mSettingsObserver;
403
Robert Greenwalt34848c02011-03-25 13:09:25 -0700404 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700405 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700406
Robert Greenwalt12c44552009-12-07 11:33:18 -0800407 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700408 public int mSimultaneity;
409 public int mType;
410 public RadioAttributes(String init) {
411 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700412 mType = Integer.parseInt(fragments[0]);
413 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700414 }
415 }
416 RadioAttributes[] mRadioAttributes;
417
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700418 // the set of network types that can only be enabled by system/sig apps
419 List mProtectedNetworks;
420
John Spurlock1f5cec72013-06-24 14:20:23 -0400421 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700422
Wink Saville32506bc2013-06-29 21:10:57 -0700423 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
424
425 TelephonyManager mTelephonyManager;
John Spurlock1f5cec72013-06-24 14:20:23 -0400426
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700427 public ConnectivityService(Context context, INetworkManagementService netd,
428 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700429 // Currently, omitting a NetworkFactory will create one internally
430 // TODO: create here when we have cleaner WiMAX support
431 this(context, netd, statsService, policyManager, null);
432 }
433
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700434 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700435 INetworkStatsService statsService, INetworkPolicyManager policyManager,
436 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800437 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800438
Wink Saville775aad62010-09-02 19:23:52 -0700439 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
440 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700441 mHandler = new InternalHandler(handlerThread.getLooper());
442 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700443
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700444 if (netFactory == null) {
445 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
446 }
447
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800448 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800449 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
450 String id = Settings.Secure.getString(context.getContentResolver(),
451 Settings.Secure.ANDROID_ID);
452 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700453 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800454 SystemProperties.set("net.hostname", name);
455 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800456 }
457
Robert Greenwalt94daa182010-09-01 11:34:05 -0700458 // read our default dns server ip
Jeff Sharkey8c870452012-09-26 22:03:49 -0700459 String dns = Settings.Global.getString(context.getContentResolver(),
460 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700461 if (dns == null || dns.length() == 0) {
462 dns = context.getResources().getString(
463 com.android.internal.R.string.config_default_dns_server);
464 }
465 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800466 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
467 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800468 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700469 }
470
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700471 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700472 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700473 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700474 mKeyStore = KeyStore.getInstance();
Wink Saville32506bc2013-06-29 21:10:57 -0700475 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700476
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700477 try {
478 mPolicyManager.registerListener(mPolicyListener);
479 } catch (RemoteException e) {
480 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700481 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700482 }
483
484 final PowerManager powerManager = (PowerManager) context.getSystemService(
485 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700486 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
487 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
488 com.android.internal.R.integer.config_networkTransitionTimeout);
489
Robert Greenwalt2034b912009-08-12 16:08:25 -0700490 mNetTrackers = new NetworkStateTracker[
491 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700492 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700493
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700494 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700495 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700496
Robert Greenwalt2034b912009-08-12 16:08:25 -0700497 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700498 String[] raStrings = context.getResources().getStringArray(
499 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700500 for (String raString : raStrings) {
501 RadioAttributes r = new RadioAttributes(raString);
Wink Saville512c2202013-07-29 15:00:57 -0700502 if (VDBG) log("raString=" + raString + " r=" + r);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700503 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800504 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700505 continue;
506 }
507 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800508 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700509 r.mType);
510 continue;
511 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700512 mRadioAttributes[r.mType] = r;
513 }
514
Wink Saville00fe5092013-04-23 14:26:51 -0700515 // TODO: What is the "correct" way to do determine if this is a wifi only device?
516 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
517 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700518 String[] naStrings = context.getResources().getStringArray(
519 com.android.internal.R.array.networkAttributes);
520 for (String naString : naStrings) {
521 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700522 NetworkConfig n = new NetworkConfig(naString);
Wink Saville512c2202013-07-29 15:00:57 -0700523 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Savillef2a62832011-04-07 14:23:45 -0700524 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800525 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700526 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700527 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700528 }
Wink Saville00fe5092013-04-23 14:26:51 -0700529 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
530 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
531 n.type);
532 continue;
533 }
Wink Savillef2a62832011-04-07 14:23:45 -0700534 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800535 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700536 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700537 continue;
538 }
Wink Savillef2a62832011-04-07 14:23:45 -0700539 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800540 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700541 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700542 continue;
543 }
Wink Savillef2a62832011-04-07 14:23:45 -0700544 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700545 mNetworksDefined++;
546 } catch(Exception e) {
547 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700548 }
549 }
Wink Saville512c2202013-07-29 15:00:57 -0700550 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700551
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700552 mProtectedNetworks = new ArrayList<Integer>();
553 int[] protectedNetworks = context.getResources().getIntArray(
554 com.android.internal.R.array.config_protectedNetworks);
555 for (int p : protectedNetworks) {
556 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
557 mProtectedNetworks.add(p);
558 } else {
559 if (DBG) loge("Ignoring protectedNetwork " + p);
560 }
561 }
562
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700563 // high priority first
564 mPriorityList = new int[mNetworksDefined];
565 {
566 int insertionPoint = mNetworksDefined-1;
567 int currentLowest = 0;
568 int nextLowest = 0;
569 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700570 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700571 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700572 if (na.priority < currentLowest) continue;
573 if (na.priority > currentLowest) {
574 if (na.priority < nextLowest || nextLowest == 0) {
575 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700576 }
577 continue;
578 }
Wink Savillef2a62832011-04-07 14:23:45 -0700579 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700580 }
581 currentLowest = nextLowest;
582 nextLowest = 0;
583 }
584 }
585
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800586 // Update mNetworkPreference according to user mannually first then overlay config.xml
587 mNetworkPreference = getPersistedNetworkPreference();
588 if (mNetworkPreference == -1) {
589 for (int n : mPriorityList) {
590 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
591 mNetworkPreference = n;
592 break;
593 }
594 }
595 if (mNetworkPreference == -1) {
596 throw new IllegalStateException(
597 "You should set at least one default Network in config.xml!");
598 }
599 }
600
Mattias Falkd697aa22011-08-23 14:15:13 +0200601 mNetRequestersPids =
602 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700603 for (int i : mPriorityList) {
Mattias Falkd697aa22011-08-23 14:15:13 +0200604 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700605 }
606
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500607 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700608
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700609 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
610 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700611
612 // Create and start trackers for hard-coded networks
613 for (int targetNetworkType : mPriorityList) {
614 final NetworkConfig config = mNetConfigs[targetNetworkType];
615 final NetworkStateTracker tracker;
616 try {
617 tracker = netFactory.createTracker(targetNetworkType, config);
618 mNetTrackers[targetNetworkType] = tracker;
619 } catch (IllegalArgumentException e) {
620 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
621 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700622 continue;
623 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700624
625 tracker.startMonitoring(context, mTrackerHandler);
626 if (config.isDefault()) {
627 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800628 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700629 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800630
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700631 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800632
Robert Greenwaltf68291a2013-07-19 14:30:49 -0700633 //set up the listener for user state for creating user VPNs
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700634 IntentFilter intentFilter = new IntentFilter();
635 intentFilter.addAction(Intent.ACTION_USER_STARTING);
636 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
637 mContext.registerReceiverAsUser(
638 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900639 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
640
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700641 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700642 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700643 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900644 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700645 } catch (RemoteException e) {
646 loge("Error registering observer :" + e);
647 }
648
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700649 if (DBG) {
650 mInetLog = new ArrayList();
651 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700652
653 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
654 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800655
John Spurlock1f5cec72013-06-24 14:20:23 -0400656 mDataConnectionStats = new DataConnectionStats(mContext);
657 mDataConnectionStats.startMonitoring();
Jason Monka5bf2842013-07-03 17:04:33 -0400658
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700659 // start network sampling ..
660 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
661 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -0700662 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700663
664 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
665 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
666
667 IntentFilter filter = new IntentFilter();
668 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
669 mContext.registerReceiver(
670 new BroadcastReceiver() {
671 @Override
672 public void onReceive(Context context, Intent intent) {
673 String action = intent.getAction();
674 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
675 mHandler.sendMessage(mHandler.obtainMessage
676 (EVENT_SAMPLE_INTERVAL_ELAPSED));
677 }
678 }
679 },
680 new IntentFilter(filter));
681
Jason Monka5bf2842013-07-03 17:04:33 -0400682 mPacManager = new PacManager(mContext);
Wink Savillecb117d32013-08-29 14:57:08 -0700683
684 filter = new IntentFilter();
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700685 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
686 mContext.registerReceiver(mProvisioningReceiver, filter);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800687 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700688
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700689 /**
690 * Factory that creates {@link NetworkStateTracker} instances using given
691 * {@link NetworkConfig}.
692 */
693 public interface NetworkFactory {
694 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
695 }
696
697 private static class DefaultNetworkFactory implements NetworkFactory {
698 private final Context mContext;
699 private final Handler mTrackerHandler;
700
701 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
702 mContext = context;
703 mTrackerHandler = trackerHandler;
704 }
705
706 @Override
707 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
708 switch (config.radio) {
709 case TYPE_WIFI:
710 return new WifiStateTracker(targetNetworkType, config.name);
711 case TYPE_MOBILE:
712 return new MobileDataStateTracker(targetNetworkType, config.name);
713 case TYPE_DUMMY:
714 return new DummyDataStateTracker(targetNetworkType, config.name);
715 case TYPE_BLUETOOTH:
716 return BluetoothTetheringDataTracker.getInstance();
717 case TYPE_WIMAX:
718 return makeWimaxStateTracker(mContext, mTrackerHandler);
719 case TYPE_ETHERNET:
720 return EthernetDataTracker.getInstance();
721 default:
722 throw new IllegalArgumentException(
723 "Trying to create a NetworkStateTracker for an unknown radio type: "
724 + config.radio);
725 }
726 }
727 }
728
729 /**
730 * Loads external WiMAX library and registers as system service, returning a
731 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
732 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
733 */
734 private static NetworkStateTracker makeWimaxStateTracker(
735 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700736 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900737 DexClassLoader wimaxClassLoader;
738 Class wimaxStateTrackerClass = null;
739 Class wimaxServiceClass = null;
740 Class wimaxManagerClass;
741 String wimaxJarLocation;
742 String wimaxLibLocation;
743 String wimaxManagerClassName;
744 String wimaxServiceClassName;
745 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800746
tk.mun093f55c2011-10-13 22:51:57 +0900747 NetworkStateTracker wimaxStateTracker = null;
748
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700749 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900750 com.android.internal.R.bool.config_wimaxEnabled);
751
752 if (isWimaxEnabled) {
753 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700754 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900755 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700756 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900757 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700758 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900759 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700760 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900761 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700762 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900763 com.android.internal.R.string.config_wimaxStateTrackerClassname);
764
Dianne Hackborndc456a62012-11-08 11:12:09 -0800765 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900766 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700767 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900768 wimaxLibLocation, ClassLoader.getSystemClassLoader());
769
770 try {
771 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
772 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
773 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
774 } catch (ClassNotFoundException ex) {
775 loge("Exception finding Wimax classes: " + ex.toString());
776 return null;
777 }
778 } catch(Resources.NotFoundException ex) {
779 loge("Wimax Resources does not exist!!! ");
780 return null;
781 }
782
783 try {
Dianne Hackborndc456a62012-11-08 11:12:09 -0800784 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900785
786 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
787 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700788 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
789 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900790
791 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
792 (new Class[] {Context.class, wimaxStateTrackerClass});
793 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700794 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900795 wmxSrvConst.setAccessible(false);
796
797 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
798
799 } catch(Exception ex) {
800 loge("Exception creating Wimax classes: " + ex.toString());
801 return null;
802 }
803 } else {
804 loge("Wimax is not enabled or not added to the network attributes!!! ");
805 return null;
806 }
807
808 return wimaxStateTracker;
809 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700810
The Android Open Source Project28527d22009-03-03 19:31:44 -0800811 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700812 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800813 * @param preference the new preference
814 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700815 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800816 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700817
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700818 mHandler.sendMessage(
819 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800820 }
821
822 public int getNetworkPreference() {
823 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700824 int preference;
825 synchronized(this) {
826 preference = mNetworkPreference;
827 }
828 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800829 }
830
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700831 private void handleSetNetworkPreference(int preference) {
832 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700833 mNetConfigs[preference] != null &&
834 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700835 if (mNetworkPreference != preference) {
836 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownc67cf562012-09-25 15:03:20 -0700837 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700838 synchronized(this) {
839 mNetworkPreference = preference;
840 }
841 enforcePreference();
842 }
843 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800844 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700845
Wink Saville4f0de1e2011-08-04 15:01:58 -0700846 private int getConnectivityChangeDelay() {
847 final ContentResolver cr = mContext.getContentResolver();
848
849 /** Check system properties for the default value then use secure settings value, if any. */
850 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey8c870452012-09-26 22:03:49 -0700851 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
852 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
853 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700854 defaultDelay);
855 }
856
The Android Open Source Project28527d22009-03-03 19:31:44 -0800857 private int getPersistedNetworkPreference() {
858 final ContentResolver cr = mContext.getContentResolver();
859
Jeff Brownc67cf562012-09-25 15:03:20 -0700860 final int networkPrefSetting = Settings.Global
861 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800862
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800863 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800864 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700865
The Android Open Source Project28527d22009-03-03 19:31:44 -0800866 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700867 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800868 * In this method, we only tear down a non-preferred network. Establishing
869 * a connection to the preferred network is taken care of when we handle
870 * the disconnect event from the non-preferred network
871 * (see {@link #handleDisconnect(NetworkInfo)}).
872 */
873 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700874 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800875 return;
876
Robert Greenwalt2034b912009-08-12 16:08:25 -0700877 if (!mNetTrackers[mNetworkPreference].isAvailable())
878 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800879
Robert Greenwalt2034b912009-08-12 16:08:25 -0700880 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700881 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700882 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700883 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800884 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700885 " in enforcePreference");
886 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700887 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800888 }
889 }
890 }
891
892 private boolean teardown(NetworkStateTracker netTracker) {
893 if (netTracker.teardown()) {
894 netTracker.setTeardownRequested(true);
895 return true;
896 } else {
897 return false;
898 }
899 }
900
901 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700902 * Check if UID should be blocked from using the network represented by the
903 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700904 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700905 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
906 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700907
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700908 final boolean networkCostly;
909 final int uidRules;
910 synchronized (mRulesLock) {
911 networkCostly = mMeteredIfaces.contains(iface);
912 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700913 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700914
915 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
916 return true;
917 }
918
919 // no restrictive rules; network is visible
920 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700921 }
922
923 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700924 * Return a filtered {@link NetworkInfo}, potentially marked
925 * {@link DetailedState#BLOCKED} based on
926 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700927 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700928 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
929 NetworkInfo info = tracker.getNetworkInfo();
930 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700931 // network is blocked; clone and override state
932 info = new NetworkInfo(info);
933 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700934 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700935 if (mLockdownTracker != null) {
936 info = mLockdownTracker.augmentNetworkInfo(info);
937 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700938 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700939 }
940
941 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800942 * Return NetworkInfo for the active (i.e., connected) network interface.
943 * It is assumed that at most one network is active at a time. If more
944 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700945 * @return the info for the active network, or {@code null} if none is
946 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800947 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700948 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800949 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700950 enforceAccessPermission();
951 final int uid = Binder.getCallingUid();
952 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800953 }
954
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700955 /**
956 * Find the first Provisioning network.
957 *
958 * @return NetworkInfo or null if none.
959 */
960 private NetworkInfo getProvisioningNetworkInfo() {
961 enforceAccessPermission();
962
963 // Find the first Provisioning Network
964 NetworkInfo provNi = null;
965 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Savilleb1a32022013-09-05 12:02:25 -0700966 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700967 provNi = ni;
968 break;
969 }
970 }
971 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
972 return provNi;
973 }
974
975 /**
976 * Find the first Provisioning network or the ActiveDefaultNetwork
977 * if there is no Provisioning network
978 *
979 * @return NetworkInfo or null if none.
980 */
981 @Override
982 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
983 enforceAccessPermission();
984
985 NetworkInfo provNi = getProvisioningNetworkInfo();
986 if (provNi == null) {
987 final int uid = Binder.getCallingUid();
988 provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
989 }
990 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
991 return provNi;
992 }
993
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700994 public NetworkInfo getActiveNetworkInfoUnfiltered() {
995 enforceAccessPermission();
996 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
997 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
998 if (tracker != null) {
999 return tracker.getNetworkInfo();
1000 }
1001 }
1002 return null;
1003 }
1004
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001005 @Override
1006 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1007 enforceConnectivityInternalPermission();
1008 return getNetworkInfo(mActiveDefaultNetwork, uid);
1009 }
1010
1011 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001012 public NetworkInfo getNetworkInfo(int networkType) {
1013 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001014 final int uid = Binder.getCallingUid();
1015 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001016 }
1017
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001018 private NetworkInfo getNetworkInfo(int networkType, int uid) {
1019 NetworkInfo info = null;
1020 if (isNetworkTypeValid(networkType)) {
1021 final NetworkStateTracker tracker = mNetTrackers[networkType];
1022 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001023 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001024 }
1025 }
1026 return info;
1027 }
1028
1029 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001030 public NetworkInfo[] getAllNetworkInfo() {
1031 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001032 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -07001033 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001034 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001035 for (NetworkStateTracker tracker : mNetTrackers) {
1036 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001037 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001038 }
1039 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001040 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001041 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001042 }
1043
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001044 @Override
1045 public boolean isNetworkSupported(int networkType) {
1046 enforceAccessPermission();
1047 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
1048 }
1049
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001050 /**
1051 * Return LinkProperties for the active (i.e., connected) default
1052 * network interface. It is assumed that at most one default network
1053 * is active at a time. If more than one is active, it is indeterminate
1054 * which will be returned.
1055 * @return the ip properties for the active network, or {@code null} if
1056 * none is active
1057 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001058 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001059 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -07001060 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001061 }
1062
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001063 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001064 public LinkProperties getLinkProperties(int networkType) {
1065 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001066 if (isNetworkTypeValid(networkType)) {
1067 final NetworkStateTracker tracker = mNetTrackers[networkType];
1068 if (tracker != null) {
1069 return tracker.getLinkProperties();
1070 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001071 }
1072 return null;
1073 }
1074
Jeff Sharkey21062e72011-05-28 20:56:34 -07001075 @Override
1076 public NetworkState[] getAllNetworkState() {
1077 enforceAccessPermission();
1078 final int uid = Binder.getCallingUid();
1079 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001080 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -07001081 for (NetworkStateTracker tracker : mNetTrackers) {
1082 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001083 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -07001084 result.add(new NetworkState(
1085 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1086 }
1087 }
1088 }
1089 return result.toArray(new NetworkState[result.size()]);
1090 }
1091
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001092 private NetworkState getNetworkStateUnchecked(int networkType) {
1093 if (isNetworkTypeValid(networkType)) {
1094 final NetworkStateTracker tracker = mNetTrackers[networkType];
1095 if (tracker != null) {
1096 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1097 tracker.getLinkCapabilities());
1098 }
1099 }
1100 return null;
1101 }
1102
1103 @Override
1104 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1105 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001106
1107 final long token = Binder.clearCallingIdentity();
1108 try {
1109 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1110 if (state != null) {
1111 try {
1112 return mPolicyManager.getNetworkQuotaInfo(state);
1113 } catch (RemoteException e) {
1114 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001115 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001116 return null;
1117 } finally {
1118 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001119 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001120 }
1121
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001122 @Override
1123 public boolean isActiveNetworkMetered() {
1124 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001125 final long token = Binder.clearCallingIdentity();
1126 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001127 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001128 } finally {
1129 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001130 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001131 }
1132
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001133 private boolean isNetworkMeteredUnchecked(int networkType) {
1134 final NetworkState state = getNetworkStateUnchecked(networkType);
1135 if (state != null) {
1136 try {
1137 return mPolicyManager.isNetworkMetered(state);
1138 } catch (RemoteException e) {
1139 }
1140 }
1141 return false;
1142 }
1143
The Android Open Source Project28527d22009-03-03 19:31:44 -08001144 public boolean setRadios(boolean turnOn) {
1145 boolean result = true;
1146 enforceChangePermission();
1147 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001148 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001149 }
1150 return result;
1151 }
1152
1153 public boolean setRadio(int netType, boolean turnOn) {
1154 enforceChangePermission();
1155 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1156 return false;
1157 }
1158 NetworkStateTracker tracker = mNetTrackers[netType];
1159 return tracker != null && tracker.setRadio(turnOn);
1160 }
1161
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001162 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1163 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001164 public void interfaceClassDataActivityChanged(String label, boolean active) {
1165 int deviceType = Integer.parseInt(label);
1166 sendDataActivityBroadcast(deviceType, active);
1167 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001168 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001169
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001170 /**
1171 * Used to notice when the calling process dies so we can self-expire
1172 *
1173 * Also used to know if the process has cleaned up after itself when
1174 * our auto-expire timer goes off. The timer has a link to an object.
1175 *
1176 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001177 private class FeatureUser implements IBinder.DeathRecipient {
1178 int mNetworkType;
1179 String mFeature;
1180 IBinder mBinder;
1181 int mPid;
1182 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001183 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001184
1185 FeatureUser(int type, String feature, IBinder binder) {
1186 super();
1187 mNetworkType = type;
1188 mFeature = feature;
1189 mBinder = binder;
1190 mPid = getCallingPid();
1191 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001192 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001193
Robert Greenwalt2034b912009-08-12 16:08:25 -07001194 try {
1195 mBinder.linkToDeath(this, 0);
1196 } catch (RemoteException e) {
1197 binderDied();
1198 }
1199 }
1200
1201 void unlinkDeathRecipient() {
1202 mBinder.unlinkToDeath(this, 0);
1203 }
1204
1205 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001206 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001207 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1208 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001209 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001210 }
1211
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001212 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001213 if (VDBG) {
1214 log("ConnectivityService FeatureUser expire(" +
1215 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1216 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1217 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001218 stopUsingNetworkFeature(this, false);
1219 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001220
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001221 public boolean isSameUser(FeatureUser u) {
1222 if (u == null) return false;
1223
1224 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1225 }
1226
1227 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1228 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1229 TextUtils.equals(mFeature, feature)) {
1230 return true;
1231 }
1232 return false;
1233 }
1234
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001235 public String toString() {
1236 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1237 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1238 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001239 }
1240
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001241 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001242 public int startUsingNetworkFeature(int networkType, String feature,
1243 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001244 long startTime = 0;
1245 if (DBG) {
1246 startTime = SystemClock.elapsedRealtime();
1247 }
Wink Savillea7d56572011-09-21 11:05:43 -07001248 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001249 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1250 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001251 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001252 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001253 try {
1254 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1255 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001256 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001257 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001258
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001259 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001260
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001261 // TODO - move this into individual networktrackers
1262 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001263
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001264 if (mLockdownEnabled) {
1265 // Since carrier APNs usually aren't available from VPN
1266 // endpoint, mark them as unavailable.
1267 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1268 }
1269
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001270 if (mProtectedNetworks.contains(usedNetworkType)) {
1271 enforceConnectivityInternalPermission();
1272 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001273
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001274 // if UID is restricted, don't allow them to bring up metered APNs
1275 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1276 final int uidRules;
1277 synchronized (mRulesLock) {
1278 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1279 }
1280 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001281 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001282 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001283
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001284 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1285 if (network != null) {
1286 Integer currentPid = new Integer(getCallingPid());
1287 if (usedNetworkType != networkType) {
1288 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001289
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001290 if (ni.isAvailable() == false) {
1291 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1292 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001293 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001294 } else {
1295 // else make the attempt anyway - probably giving REQUEST_STARTED below
1296 if (DBG) {
1297 log("special network not available, but try anyway ni=" +
1298 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001299 }
1300 }
1301 }
1302
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001303 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001304
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001305 synchronized(this) {
1306 boolean addToList = true;
1307 if (restoreTimer < 0) {
1308 // In case there is no timer is specified for the feature,
1309 // make sure we don't add duplicate entry with the same request.
1310 for (FeatureUser u : mFeatureUsers) {
1311 if (u.isSameUser(f)) {
1312 // Duplicate user is found. Do not add.
1313 addToList = false;
1314 break;
1315 }
1316 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001317 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001318
1319 if (addToList) mFeatureUsers.add(f);
1320 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1321 // this gets used for per-pid dns when connected
1322 mNetRequestersPids[usedNetworkType].add(currentPid);
1323 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001324 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001325
1326 if (restoreTimer >= 0) {
1327 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1328 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1329 }
1330
1331 if ((ni.isConnectedOrConnecting() == true) &&
1332 !network.isTeardownRequested()) {
1333 if (ni.isConnected() == true) {
1334 final long token = Binder.clearCallingIdentity();
1335 try {
1336 // add the pid-specific dns
1337 handleDnsConfigurationChange(usedNetworkType);
1338 if (VDBG) log("special network already active");
1339 } finally {
1340 Binder.restoreCallingIdentity(token);
1341 }
Wink Saville64e3f782012-07-10 12:37:54 -07001342 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001343 }
1344 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001345 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001346 }
1347
1348 // check if the radio in play can make another contact
1349 // assume if cannot for now
1350
1351 if (DBG) {
1352 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1353 feature);
1354 }
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001355 if (network.reconnect()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001356 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001357 return PhoneConstants.APN_REQUEST_STARTED;
1358 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001359 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001360 return PhoneConstants.APN_REQUEST_FAILED;
1361 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001362 } else {
1363 // need to remember this unsupported request so we respond appropriately on stop
1364 synchronized(this) {
1365 mFeatureUsers.add(f);
1366 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1367 // this gets used for per-pid dns when connected
1368 mNetRequestersPids[usedNetworkType].add(currentPid);
1369 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001370 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001371 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001372 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001373 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001374 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001375 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
Wink Saville64e3f782012-07-10 12:37:54 -07001376 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001377 } finally {
1378 if (DBG) {
1379 final long execTime = SystemClock.elapsedRealtime() - startTime;
1380 if (execTime > 250) {
1381 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1382 } else {
1383 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1384 }
1385 }
1386 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001387 }
1388
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001389 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001390 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001391 enforceChangePermission();
1392
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001393 int pid = getCallingPid();
1394 int uid = getCallingUid();
1395
1396 FeatureUser u = null;
1397 boolean found = false;
1398
1399 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001400 for (FeatureUser x : mFeatureUsers) {
1401 if (x.isSameUser(pid, uid, networkType, feature)) {
1402 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001403 found = true;
1404 break;
1405 }
1406 }
1407 }
1408 if (found && u != null) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001409 if (VDBG) log("stopUsingNetworkFeature: X");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001410 // stop regardless of how many other time this proc had called start
1411 return stopUsingNetworkFeature(u, true);
1412 } else {
1413 // none found!
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001414 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001415 return 1;
1416 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001417 }
1418
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001419 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1420 int networkType = u.mNetworkType;
1421 String feature = u.mFeature;
1422 int pid = u.mPid;
1423 int uid = u.mUid;
1424
1425 NetworkStateTracker tracker = null;
1426 boolean callTeardown = false; // used to carry our decision outside of sync block
1427
Wink Savillea7d56572011-09-21 11:05:43 -07001428 if (VDBG) {
1429 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001430 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001431
The Android Open Source Project28527d22009-03-03 19:31:44 -08001432 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001433 if (DBG) {
1434 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1435 ", net is invalid");
1436 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001437 return -1;
1438 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001439
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001440 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1441 // sync block
1442 synchronized(this) {
1443 // check if this process still has an outstanding start request
1444 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001445 if (VDBG) {
1446 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1447 ", ignoring");
1448 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001449 return 1;
1450 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001451 u.unlinkDeathRecipient();
1452 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1453 // If we care about duplicate requests, check for that here.
1454 //
1455 // This is done to support the extension of a request - the app
1456 // can request we start the network feature again and renew the
1457 // auto-shutoff delay. Normal "stop" calls from the app though
1458 // do not pay attention to duplicate requests - in effect the
1459 // API does not refcount and a single stop will counter multiple starts.
1460 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001461 for (FeatureUser x : mFeatureUsers) {
1462 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001463 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001464 return 1;
1465 }
1466 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001467 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001468
repo syncf5de5572011-07-29 23:55:49 -07001469 // TODO - move to individual network trackers
1470 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1471
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001472 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001473 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001474 if (DBG) {
1475 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1476 " no known tracker for used net type " + usedNetworkType);
1477 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001478 return -1;
1479 }
1480 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001481 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001482 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalte767d812013-02-12 17:18:25 -08001483
1484 final long token = Binder.clearCallingIdentity();
1485 try {
1486 reassessPidDns(pid, true);
1487 } finally {
1488 Binder.restoreCallingIdentity(token);
1489 }
Mattias Falkd697aa22011-08-23 14:15:13 +02001490 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001491 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001492 if (VDBG) {
1493 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1494 " others still using it");
1495 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001496 return 1;
1497 }
1498 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001499 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001500 if (DBG) {
1501 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1502 " not a known feature - dropping");
1503 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001504 }
1505 }
Wink Savillea7d56572011-09-21 11:05:43 -07001506
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001507 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001508 if (DBG) {
1509 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1510 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001511 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001512 return 1;
1513 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001514 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001515 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001516 }
1517
1518 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001519 * @deprecated use requestRouteToHostAddress instead
1520 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001521 * Ensure that a network route exists to deliver traffic to the specified
1522 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001523 * @param networkType the type of the network over which traffic to the
1524 * specified host is to be routed
1525 * @param hostAddress the IP address of the host to which the route is
1526 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001527 * @return {@code true} on success, {@code false} on failure
1528 */
1529 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001530 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1531
1532 if (inetAddress == null) {
1533 return false;
1534 }
1535
1536 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1537 }
1538
1539 /**
1540 * Ensure that a network route exists to deliver traffic to the specified
1541 * host via the specified network interface.
1542 * @param networkType the type of the network over which traffic to the
1543 * specified host is to be routed
1544 * @param hostAddress the IP address of the host to which the route is
1545 * desired
1546 * @return {@code true} on success, {@code false} on failure
1547 */
1548 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001549 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001550 if (mProtectedNetworks.contains(networkType)) {
1551 enforceConnectivityInternalPermission();
1552 }
1553
The Android Open Source Project28527d22009-03-03 19:31:44 -08001554 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001555 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001556 return false;
1557 }
1558 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001559 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001560
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001561 if (tracker == null || (netState != DetailedState.CONNECTED &&
1562 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001563 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001564 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07001565 log("requestRouteToHostAddress on down network "
1566 + "(" + networkType + ") - dropped"
1567 + " tracker=" + tracker
1568 + " netState=" + netState
1569 + " isTeardownRequested="
1570 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001571 }
1572 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001573 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001574 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001575 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001576 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001577 LinkProperties lp = tracker.getLinkProperties();
Chad Brubaker49db4222013-07-15 16:34:04 -07001578 boolean ok = addRouteToAddress(lp, addr, EXEMPT);
Wink Saville32506bc2013-06-29 21:10:57 -07001579 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1580 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001581 } catch (UnknownHostException e) {
1582 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1583 } finally {
1584 Binder.restoreCallingIdentity(token);
1585 }
Wink Saville32506bc2013-06-29 21:10:57 -07001586 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001587 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001588 }
1589
Chad Brubaker49db4222013-07-15 16:34:04 -07001590 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1591 boolean exempt) {
1592 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001593 }
1594
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001595 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001596 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001597 }
1598
Chad Brubaker49db4222013-07-15 16:34:04 -07001599 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1600 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001601 }
1602
1603 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001604 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
Robert Greenwalt98107422011-07-22 11:55:33 -07001605 }
1606
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001607 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
Chad Brubaker49db4222013-07-15 16:34:04 -07001608 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001609 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001610 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001611 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001612 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001613 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001614 if (bestRoute.getGateway().equals(addr)) {
1615 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001616 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001617 } else {
1618 // if we will connect to this through another route, add a direct route
1619 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001620 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001621 }
1622 }
Chad Brubaker49db4222013-07-15 16:34:04 -07001623 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001624 }
1625
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001626 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
Chad Brubaker49db4222013-07-15 16:34:04 -07001627 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001628 if ((lp == null) || (r == null)) {
1629 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001630 return false;
1631 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001632
1633 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001634 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001635 return false;
1636 }
1637
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001638 String ifaceName = r.getInterface();
1639 if(ifaceName == null) {
1640 loge("Error modifying route - no interface name");
1641 return false;
1642 }
Robert Greenwalt59070cf2013-04-11 13:48:16 -07001643 if (r.hasGateway()) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001644 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001645 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001646 if (bestRoute.getGateway().equals(r.getGateway())) {
1647 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001648 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001649 } else {
1650 // if we will connect to our gateway through another route, add a direct
1651 // route to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001652 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1653 bestRoute.getGateway(),
1654 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001655 }
Chad Brubaker49db4222013-07-15 16:34:04 -07001656 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001657 }
1658 }
1659 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001660 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001661 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001662 if (toDefaultTable) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001663 synchronized (mRoutesLock) {
1664 // only track default table - only one apps can effect
1665 mAddedRoutes.add(r);
1666 mNetd.addRoute(ifaceName, r);
1667 if (exempt) {
1668 LinkAddress dest = r.getDestination();
1669 if (!mExemptAddresses.contains(dest)) {
1670 mNetd.setHostExemption(dest);
1671 mExemptAddresses.add(dest);
1672 }
1673 }
1674 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001675 } else {
1676 mNetd.addSecondaryRoute(ifaceName, r);
1677 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001678 } catch (Exception e) {
1679 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001680 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001681 return false;
1682 }
1683 } else {
1684 // if we remove this one and there are no more like it, then refcount==0 and
1685 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001686 if (toDefaultTable) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001687 synchronized (mRoutesLock) {
1688 mAddedRoutes.remove(r);
1689 if (mAddedRoutes.contains(r) == false) {
1690 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1691 try {
1692 mNetd.removeRoute(ifaceName, r);
1693 LinkAddress dest = r.getDestination();
1694 if (mExemptAddresses.contains(dest)) {
1695 mNetd.clearHostExemption(dest);
1696 mExemptAddresses.remove(dest);
1697 }
1698 } catch (Exception e) {
1699 // never crash - catch them all
1700 if (VDBG) loge("Exception trying to remove a route: " + e);
1701 return false;
1702 }
1703 } else {
1704 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001705 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001706 }
1707 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001708 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001709 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001710 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001711 } catch (Exception e) {
1712 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001713 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001714 return false;
1715 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001716 }
1717 }
1718 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001719 }
1720
1721 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001722 * @see ConnectivityManager#getMobileDataEnabled()
1723 */
1724 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001725 // TODO: This detail should probably be in DataConnectionTracker's
1726 // which is where we store the value and maybe make this
1727 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001728 enforceAccessPermission();
Jeff Sharkey8b361572012-09-26 15:54:06 -07001729 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1730 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001731 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001732 return retVal;
1733 }
1734
Robert Greenwalt34848c02011-03-25 13:09:25 -07001735 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001736 enforceConnectivityInternalPermission();
1737
Robert Greenwalt34848c02011-03-25 13:09:25 -07001738 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1739 (met ? ENABLED : DISABLED), networkType));
1740 }
1741
1742 private void handleSetDependencyMet(int networkType, boolean met) {
1743 if (mNetTrackers[networkType] != null) {
1744 if (DBG) {
1745 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1746 }
1747 mNetTrackers[networkType].setDependencyMet(met);
1748 }
1749 }
1750
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001751 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1752 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001753 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001754 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001755 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001756 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001757 }
1758
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001759 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001760 // skip update when we've already applied rules
1761 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1762 if (oldRules == uidRules) return;
1763
1764 mUidRules.put(uid, uidRules);
1765 }
1766
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001767 // TODO: notify UID when it has requested targeted updates
1768 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001769
1770 @Override
1771 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001772 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001773 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001774 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001775 }
1776
1777 synchronized (mRulesLock) {
1778 mMeteredIfaces.clear();
1779 for (String iface : meteredIfaces) {
1780 mMeteredIfaces.add(iface);
1781 }
1782 }
1783 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001784
1785 @Override
1786 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1787 // caller is NPMS, since we only register with them
1788 if (LOGD_RULES) {
1789 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1790 }
1791
1792 // kick off connectivity change broadcast for active network, since
1793 // global background policy change is radical.
1794 final int networkType = mActiveDefaultNetwork;
1795 if (isNetworkTypeValid(networkType)) {
1796 final NetworkStateTracker tracker = mNetTrackers[networkType];
1797 if (tracker != null) {
1798 final NetworkInfo info = tracker.getNetworkInfo();
1799 if (info != null && info.isConnected()) {
1800 sendConnectedBroadcast(info);
1801 }
1802 }
1803 }
1804 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001805 };
1806
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001807 /**
1808 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1809 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001810 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001811 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001812 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001813
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001814 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001815 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001816 }
1817
1818 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001819 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001820 if (VDBG) {
1821 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001822 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001823 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1824 }
tk.mun5eee1042012-01-06 10:43:52 +09001825 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1826 if (VDBG) {
1827 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1828 }
1829 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1830 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001831 }
1832
1833 @Override
1834 public void setPolicyDataEnable(int networkType, boolean enabled) {
1835 // only someone like NPMS should only be calling us
1836 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1837
1838 mHandler.sendMessage(mHandler.obtainMessage(
1839 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1840 }
1841
1842 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1843 if (isNetworkTypeValid(networkType)) {
1844 final NetworkStateTracker tracker = mNetTrackers[networkType];
1845 if (tracker != null) {
1846 tracker.setPolicyDataEnable(enabled);
1847 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001848 }
1849 }
1850
The Android Open Source Project28527d22009-03-03 19:31:44 -08001851 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001852 mContext.enforceCallingOrSelfPermission(
1853 android.Manifest.permission.ACCESS_NETWORK_STATE,
1854 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001855 }
1856
1857 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001858 mContext.enforceCallingOrSelfPermission(
1859 android.Manifest.permission.CHANGE_NETWORK_STATE,
1860 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001861 }
1862
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001863 // TODO Make this a special check when it goes public
1864 private void enforceTetherChangePermission() {
1865 mContext.enforceCallingOrSelfPermission(
1866 android.Manifest.permission.CHANGE_NETWORK_STATE,
1867 "ConnectivityService");
1868 }
1869
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001870 private void enforceTetherAccessPermission() {
1871 mContext.enforceCallingOrSelfPermission(
1872 android.Manifest.permission.ACCESS_NETWORK_STATE,
1873 "ConnectivityService");
1874 }
1875
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001876 private void enforceConnectivityInternalPermission() {
1877 mContext.enforceCallingOrSelfPermission(
1878 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1879 "ConnectivityService");
1880 }
1881
Chad Brubaker11f22252013-07-11 13:29:30 -07001882 private void enforceMarkNetworkSocketPermission() {
1883 //Media server special case
1884 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1885 return;
1886 }
1887 mContext.enforceCallingOrSelfPermission(
1888 android.Manifest.permission.MARK_NETWORK_SOCKET,
1889 "ConnectivityService");
1890 }
1891
The Android Open Source Project28527d22009-03-03 19:31:44 -08001892 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001893 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1894 * network, we ignore it. If it is for the active network, we send out a
1895 * broadcast. But first, we check whether it might be possible to connect
1896 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001897 * @param info the {@code NetworkInfo} for the network
1898 */
1899 private void handleDisconnect(NetworkInfo info) {
1900
Robert Greenwalt2034b912009-08-12 16:08:25 -07001901 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001902
Robert Greenwalt2034b912009-08-12 16:08:25 -07001903 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Baie2462442012-06-28 15:26:19 -07001904
1905 // Remove idletimer previously setup in {@code handleConnect}
1906 removeDataActivityTracking(prevNetType);
1907
The Android Open Source Project28527d22009-03-03 19:31:44 -08001908 /*
1909 * If the disconnected network is not the active one, then don't report
1910 * this as a loss of connectivity. What probably happened is that we're
1911 * getting the disconnect for a network that we explicitly disabled
1912 * in accordance with network preference policies.
1913 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001914 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkd697aa22011-08-23 14:15:13 +02001915 List<Integer> pids = mNetRequestersPids[prevNetType];
1916 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001917 // will remove them because the net's no longer connected
1918 // need to do this now as only now do we know the pids and
1919 // can properly null things that are no longer referenced.
1920 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001921 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001922 }
1923
The Android Open Source Project28527d22009-03-03 19:31:44 -08001924 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001925 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001926 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001927 if (info.isFailover()) {
1928 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1929 info.setFailover(false);
1930 }
1931 if (info.getReason() != null) {
1932 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1933 }
1934 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001935 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1936 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001937 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001938
Robert Greenwalt34848c02011-03-25 13:09:25 -07001939 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001940 tryFailover(prevNetType);
1941 if (mActiveDefaultNetwork != -1) {
1942 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001943 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1944 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001945 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001946 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1947 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001948 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001949 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001950
1951 // Reset interface if no other connections are using the same interface
1952 boolean doReset = true;
1953 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1954 if (linkProperties != null) {
1955 String oldIface = linkProperties.getInterfaceName();
1956 if (TextUtils.isEmpty(oldIface) == false) {
1957 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1958 if (networkStateTracker == null) continue;
1959 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1960 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1961 LinkProperties l = networkStateTracker.getLinkProperties();
1962 if (l == null) continue;
1963 if (oldIface.equals(l.getInterfaceName())) {
1964 doReset = false;
1965 break;
1966 }
1967 }
1968 }
1969 }
1970 }
1971
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001972 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001973 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001974
Jeff Sharkey971cd162011-08-29 16:02:57 -07001975 final Intent immediateIntent = new Intent(intent);
1976 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1977 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001978 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001979 /*
1980 * If the failover network is already connected, then immediately send
1981 * out a followup broadcast indicating successful failover
1982 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001983 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001984 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1985 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001986 }
1987 }
1988
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001989 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001990 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001991 * If this is a default network, check if other defaults are available.
1992 * Try to reconnect on all available and let them hash it out when
1993 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001994 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001995 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001996 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001997 if (DBG) {
1998 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
1999 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002000 mActiveDefaultNetwork = -1;
2001 }
2002
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002003 // don't signal a reconnect for anything lower or equal priority than our
2004 // current connected default
2005 // TODO - don't filter by priority now - nice optimization but risky
2006// int currentPriority = -1;
2007// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002008// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002009// }
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002010
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002011 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07002012 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002013 if (mNetConfigs[checkType] == null) continue;
2014 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08002015 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08002016
2017// Enabling the isAvailable() optimization caused mobile to not get
2018// selected if it was in the middle of error handling. Specifically
2019// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2020// would not be available and we wouldn't get connected to anything.
2021// So removing the isAvailable() optimization below for now. TODO: This
2022// optimization should work and we need to investigate why it doesn't work.
2023// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2024// complete before it is really complete.
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002025
Wink Saville72a95b92011-01-26 15:43:49 -08002026// if (!mNetTrackers[checkType].isAvailable()) continue;
2027
Robert Greenwalt34848c02011-03-25 13:09:25 -07002028// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002029
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002030 NetworkStateTracker checkTracker = mNetTrackers[checkType];
2031 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2032 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2033 checkInfo.setFailover(true);
2034 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002035 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002036 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002037 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002038 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002039 }
2040
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002041 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002042 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07002043 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2044 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002045 }
2046
Wink Saville4f0de1e2011-08-04 15:01:58 -07002047 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002048 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2049 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002050 }
2051
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002052 private void sendInetConditionBroadcast(NetworkInfo info) {
2053 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2054 }
2055
Wink Saville4f0de1e2011-08-04 15:01:58 -07002056 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002057 if (mLockdownTracker != null) {
2058 info = mLockdownTracker.augmentNetworkInfo(info);
2059 }
2060
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002061 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002062 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002063 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002064 if (info.isFailover()) {
2065 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2066 info.setFailover(false);
2067 }
2068 if (info.getReason() != null) {
2069 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2070 }
2071 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002072 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2073 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002074 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002075 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002076 return intent;
2077 }
2078
2079 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2080 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2081 }
2082
2083 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2084 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002085 }
2086
Haoyu Baib5da5752012-06-20 14:29:57 -07002087 private void sendDataActivityBroadcast(int deviceType, boolean active) {
2088 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2089 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2090 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002091 final long ident = Binder.clearCallingIdentity();
2092 try {
2093 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2094 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2095 } finally {
2096 Binder.restoreCallingIdentity(ident);
2097 }
Haoyu Baib5da5752012-06-20 14:29:57 -07002098 }
2099
The Android Open Source Project28527d22009-03-03 19:31:44 -08002100 /**
2101 * Called when an attempt to fail over to another network has failed.
2102 * @param info the {@link NetworkInfo} for the failed network
2103 */
2104 private void handleConnectionFailure(NetworkInfo info) {
2105 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002106
Robert Greenwalt2034b912009-08-12 16:08:25 -07002107 String reason = info.getReason();
2108 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07002109
Robert Greenwalte981bc52010-10-08 16:35:52 -07002110 String reasonText;
2111 if (reason == null) {
2112 reasonText = ".";
2113 } else {
2114 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08002115 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002116 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002117
2118 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002119 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002120 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002121 if (getActiveNetworkInfo() == null) {
2122 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2123 }
2124 if (reason != null) {
2125 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2126 }
2127 if (extraInfo != null) {
2128 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2129 }
2130 if (info.isFailover()) {
2131 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2132 info.setFailover(false);
2133 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002134
Robert Greenwalt34848c02011-03-25 13:09:25 -07002135 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002136 tryFailover(info.getType());
2137 if (mActiveDefaultNetwork != -1) {
2138 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002139 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2140 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002141 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002142 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2143 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002144 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002145
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002146 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002147
2148 final Intent immediateIntent = new Intent(intent);
2149 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2150 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002151 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002152 /*
2153 * If the failover network is already connected, then immediately send
2154 * out a followup broadcast indicating successful failover
2155 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002156 if (mActiveDefaultNetwork != -1) {
2157 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002158 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002159 }
2160
2161 private void sendStickyBroadcast(Intent intent) {
2162 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002163 if (!mSystemReady) {
2164 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002165 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002166 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002167 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002168 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002169 }
2170
Dianne Hackborne588ca12012-09-04 18:48:37 -07002171 final long ident = Binder.clearCallingIdentity();
2172 try {
2173 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2174 } finally {
2175 Binder.restoreCallingIdentity(ident);
2176 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002177 }
2178 }
2179
Wink Saville4f0de1e2011-08-04 15:01:58 -07002180 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2181 if (delayMs <= 0) {
2182 sendStickyBroadcast(intent);
2183 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002184 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002185 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2186 + intent.getAction());
2187 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002188 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2189 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2190 }
2191 }
2192
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002193 void systemReady() {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002194 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2195 loadGlobalProxy();
2196
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002197 synchronized(this) {
2198 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002199 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002200 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002201 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002202 }
2203 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002204 // load the global proxy at startup
2205 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002206
2207 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2208 // for user to unlock device.
2209 if (!updateLockdownVpn()) {
2210 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2211 mContext.registerReceiver(mUserPresentReceiver, filter);
2212 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002213 }
2214
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002215 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2216 @Override
2217 public void onReceive(Context context, Intent intent) {
2218 // Try creating lockdown tracker, since user present usually means
2219 // unlocked keystore.
2220 if (updateLockdownVpn()) {
2221 mContext.unregisterReceiver(this);
2222 }
2223 }
2224 };
2225
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002226 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002227 if (((type != mNetworkPreference)
2228 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2229 || (mNetworkPreference == mActiveDefaultNetwork)) {
2230 return false;
2231 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002232 return true;
2233 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002234
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002235 private void handleConnect(NetworkInfo info) {
2236 final int newNetType = info.getType();
2237
2238 setupDataActivityTracking(newNetType);
Haoyu Baie2462442012-06-28 15:26:19 -07002239
The Android Open Source Project28527d22009-03-03 19:31:44 -08002240 // snapshot isFailover, because sendConnectedBroadcast() resets it
2241 boolean isFailover = info.isFailover();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002242 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002243 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002244
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002245 if (VDBG) {
2246 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2247 + " isFailover" + isFailover);
2248 }
2249
Robert Greenwalt2034b912009-08-12 16:08:25 -07002250 // if this is a default net and other default is running
2251 // kill the one not preferred
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002252 if (mNetConfigs[newNetType].isDefault()) {
2253 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2254 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002255 // tear down the other
2256 NetworkStateTracker otherNet =
2257 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002258 if (DBG) {
2259 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002260 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002261 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002262 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002263 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002264 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002265 return;
2266 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002267 } else {
2268 // don't accept this one
2269 if (VDBG) {
2270 log("Not broadcasting CONNECT_ACTION " +
2271 "to torn down network " + info.getTypeName());
2272 }
2273 teardown(thisNet);
2274 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002275 }
2276 }
2277 synchronized (ConnectivityService.this) {
2278 // have a new default network, release the transition wakelock in a second
2279 // if it's held. The second pause is to allow apps to reconnect over the
2280 // new network
2281 if (mNetTransitionWakeLock.isHeld()) {
2282 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002283 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002284 mNetTransitionWakeLockSerialNumber, 0),
2285 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002286 }
2287 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002288 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002289 // this will cause us to come up initially as unconnected and switching
2290 // to connected after our normal pause unless somebody reports us as reall
2291 // disconnected
2292 mDefaultInetConditionPublished = 0;
2293 mDefaultConnectionSequence++;
2294 mInetConditionChangeInFlight = false;
2295 // Don't do this - if we never sign in stay, grey
2296 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002297 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002298 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002299 updateNetworkSettings(thisNet);
sy.yun4aa73922013-09-02 05:24:09 +09002300 updateMtuSizeSettings(thisNet);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002301 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002302 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002303
2304 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002305 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002306 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002307 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002308 } catch (RemoteException e) {
2309 // ignored; service lives in system_server
2310 }
2311 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002312 }
2313
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002314 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2315 if (DBG) log("Captive portal check " + info);
2316 int type = info.getType();
2317 final NetworkStateTracker thisNet = mNetTrackers[type];
2318 if (mNetConfigs[type].isDefault()) {
2319 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2320 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2321 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002322 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002323 return;
2324 } else {
2325 if (DBG) log("Tear down low priority net " + info.getTypeName());
2326 teardown(thisNet);
2327 return;
2328 }
2329 }
2330 }
2331
Wink Saville674777e2013-08-07 16:22:47 -07002332 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002333 thisNet.captivePortalCheckComplete();
2334 }
2335
2336 /** @hide */
Wink Saville674777e2013-08-07 16:22:47 -07002337 @Override
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002338 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002339 enforceConnectivityInternalPermission();
Wink Saville674777e2013-08-07 16:22:47 -07002340 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002341 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002342 }
2343
Wink Saville674777e2013-08-07 16:22:47 -07002344 /** @hide */
2345 @Override
2346 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2347 enforceConnectivityInternalPermission();
2348 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2349 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2350 }
2351
The Android Open Source Project28527d22009-03-03 19:31:44 -08002352 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002353 * Setup data activity tracking for the given network interface.
2354 *
2355 * Every {@code setupDataActivityTracking} should be paired with a
2356 * {@link removeDataActivityTracking} for cleanup.
2357 */
2358 private void setupDataActivityTracking(int type) {
2359 final NetworkStateTracker thisNet = mNetTrackers[type];
2360 final String iface = thisNet.getLinkProperties().getInterfaceName();
2361
2362 final int timeout;
2363
2364 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002365 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2366 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Baie2462442012-06-28 15:26:19 -07002367 0);
2368 // Canonicalize mobile network type
2369 type = ConnectivityManager.TYPE_MOBILE;
2370 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002371 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2372 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Baie2462442012-06-28 15:26:19 -07002373 0);
2374 } else {
2375 // do not track any other networks
2376 timeout = 0;
2377 }
2378
2379 if (timeout > 0 && iface != null) {
2380 try {
2381 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2382 } catch (RemoteException e) {
2383 }
2384 }
2385 }
2386
2387 /**
2388 * Remove data activity tracking when network disconnects.
2389 */
2390 private void removeDataActivityTracking(int type) {
2391 final NetworkStateTracker net = mNetTrackers[type];
2392 final String iface = net.getLinkProperties().getInterfaceName();
2393
2394 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2395 ConnectivityManager.TYPE_WIFI == type)) {
2396 try {
2397 // the call fails silently if no idletimer setup for this interface
2398 mNetd.removeIdleTimer(iface);
2399 } catch (RemoteException e) {
2400 }
2401 }
2402 }
2403
2404 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002405 * After a change in the connectivity state of a network. We're mainly
2406 * concerned with making sure that the list of DNS servers is set up
2407 * according to which networks are connected, and ensuring that the
2408 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002409 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002410 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002411 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubaker49db4222013-07-15 16:34:04 -07002412 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002413 if (VDBG) {
2414 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2415 + " resetMask=" + resetMask);
2416 }
Wink Saville051a6642011-07-13 13:44:13 -07002417
The Android Open Source Project28527d22009-03-03 19:31:44 -08002418 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002419 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002420 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002421 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002422 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002423
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002424 LinkProperties curLp = mCurrentLinkProperties[netType];
2425 LinkProperties newLp = null;
2426
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002427 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002428 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002429 if (VDBG) {
2430 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2431 " doReset=" + doReset + " resetMask=" + resetMask +
2432 "\n curLp=" + curLp +
2433 "\n newLp=" + newLp);
2434 }
2435
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002436 if (curLp != null) {
2437 if (curLp.isIdenticalInterfaceName(newLp)) {
2438 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2439 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2440 for (LinkAddress linkAddr : car.removed) {
2441 if (linkAddr.getAddress() instanceof Inet4Address) {
2442 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2443 }
2444 if (linkAddr.getAddress() instanceof Inet6Address) {
2445 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2446 }
Wink Saville051a6642011-07-13 13:44:13 -07002447 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002448 if (DBG) {
2449 log("handleConnectivityChange: addresses changed" +
2450 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2451 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002452 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002453 } else {
2454 if (DBG) {
2455 log("handleConnectivityChange: address are the same reset per doReset" +
2456 " linkProperty[" + netType + "]:" +
2457 " resetMask=" + resetMask);
2458 }
Wink Saville051a6642011-07-13 13:44:13 -07002459 }
2460 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002461 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002462 if (DBG) {
2463 log("handleConnectivityChange: interface not not equivalent reset both" +
2464 " linkProperty[" + netType + "]:" +
2465 " resetMask=" + resetMask);
2466 }
Wink Saville051a6642011-07-13 13:44:13 -07002467 }
Wink Saville051a6642011-07-13 13:44:13 -07002468 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002469 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002470 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002471 }
2472 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002473 if (VDBG) {
2474 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2475 " doReset=" + doReset + " resetMask=" + resetMask +
2476 "\n curLp=" + curLp +
2477 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002478 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002479 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002480 mCurrentLinkProperties[netType] = newLp;
Chad Brubaker49db4222013-07-15 16:34:04 -07002481 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002482
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002483 if (resetMask != 0 || resetDns) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002484 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwalt4398f342013-05-23 18:33:06 -07002485 if (curLp != null) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002486 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwalt4398f342013-05-23 18:33:06 -07002487 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti63839822013-03-20 19:22:58 +09002488 if (TextUtils.isEmpty(iface) == false) {
2489 if (resetMask != 0) {
2490 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2491 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002492
Lorenzo Colitti63839822013-03-20 19:22:58 +09002493 // Tell VPN the interface is down. It is a temporary
2494 // but effective fix to make VPN aware of the change.
2495 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07002496 synchronized(mVpns) {
2497 for (int i = 0; i < mVpns.size(); i++) {
2498 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2499 }
2500 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002501 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002502 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002503 if (resetDns) {
2504 flushVmDnsCache();
2505 if (VDBG) log("resetting DNS cache for " + iface);
2506 try {
2507 mNetd.flushInterfaceDnsCache(iface);
2508 } catch (Exception e) {
2509 // never crash - catch them all
2510 if (DBG) loge("Exception resetting dns cache: " + e);
2511 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002512 }
Robert Greenwalt4398f342013-05-23 18:33:06 -07002513 } else {
2514 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002515 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002516 }
2517 }
2518 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002519
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002520 // Update 464xlat state.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002521 NetworkStateTracker tracker = mNetTrackers[netType];
2522 if (mClat.requiresClat(netType, tracker)) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002523
Lorenzo Colitti4118d082013-03-28 14:13:43 +09002524 // If the connection was previously using clat, but is not using it now, stop the clat
2525 // daemon. Normally, this happens automatically when the connection disconnects, but if
2526 // the disconnect is not reported, or if the connection's LinkProperties changed for
2527 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2528 // still be running. If it's not running, then stopping it is a no-op.
2529 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2530 mClat.stopClat();
2531 }
2532 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002533 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2534 mClat.startClat(tracker);
2535 } else {
2536 mClat.stopClat();
2537 }
2538 }
2539
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002540 // TODO: Temporary notifying upstread change to Tethering.
2541 // @see bug/4455071
2542 /** Notify TetheringService if interface name has been changed. */
2543 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002544 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002545 if (isTetheringSupported()) {
2546 mTethering.handleTetherIfaceChange();
2547 }
2548 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002549 }
2550
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002551 /**
2552 * Add and remove routes using the old properties (null if not previously connected),
2553 * new properties (null if becoming disconnected). May even be double null, which
2554 * is a noop.
2555 * Uses isLinkDefault to determine if default routes should be set or conversely if
2556 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002557 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002558 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002559 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubaker49db4222013-07-15 16:34:04 -07002560 boolean isLinkDefault, boolean exempt) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002561 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002562 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2563 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002564 if (curLp != null) {
2565 // check for the delta between the current set and the new
Lorenzo Colittie1b47422013-07-31 23:23:21 +09002566 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002567 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002568 } else if (newLp != null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002569 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002570 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002571 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002572
Robert Greenwalt8d777252011-08-15 12:31:55 -07002573 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2574
Robert Greenwalt98107422011-07-22 11:55:33 -07002575 for (RouteInfo r : routeDiff.removed) {
2576 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002577 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002578 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2579 }
2580 if (isLinkDefault == false) {
2581 // remove from a secondary route table
2582 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002583 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002584 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002585
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002586 if (!isLinkDefault) {
2587 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002588 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002589 // routes changed - remove all old dns entries and add new
2590 if (curLp != null) {
2591 for (InetAddress oldDns : curLp.getDnses()) {
2592 removeRouteToAddress(curLp, oldDns);
2593 }
2594 }
2595 if (newLp != null) {
2596 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002597 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07002598 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002599 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002600 } else {
2601 // no change in routes, check for change in dns themselves
2602 for (InetAddress oldDns : dnsDiff.removed) {
2603 removeRouteToAddress(curLp, oldDns);
2604 }
2605 for (InetAddress newDns : dnsDiff.added) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002606 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002607 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002608 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002609 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002610
2611 for (RouteInfo r : routeDiff.added) {
2612 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002613 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002614 } else {
2615 // add to a secondary route table
Chad Brubaker49db4222013-07-15 16:34:04 -07002616 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002617
2618 // many radios add a default route even when we don't want one.
2619 // remove the default route unless somebody else has asked for it
2620 String ifaceName = newLp.getInterfaceName();
Chad Brubaker49db4222013-07-15 16:34:04 -07002621 synchronized (mRoutesLock) {
2622 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2623 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2624 try {
2625 mNetd.removeRoute(ifaceName, r);
2626 } catch (Exception e) {
2627 // never crash - catch them all
2628 if (DBG) loge("Exception trying to remove a route: " + e);
2629 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002630 }
2631 }
2632 }
2633 }
2634
Robert Greenwalt8d777252011-08-15 12:31:55 -07002635 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002636 }
2637
sy.yun4aa73922013-09-02 05:24:09 +09002638 /**
2639 * Reads the network specific MTU size from reources.
2640 * and set it on it's iface.
2641 */
2642 private void updateMtuSizeSettings(NetworkStateTracker nt) {
2643 final String iface = nt.getLinkProperties().getInterfaceName();
2644 final int mtu = nt.getLinkProperties().getMtu();
2645
2646 if (mtu < 68 || mtu > 10000) {
2647 loge("Unexpected mtu value: " + nt);
2648 return;
2649 }
2650
2651 try {
2652 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2653 mNetd.setMtu(iface, mtu);
2654 } catch (Exception e) {
2655 Slog.e(TAG, "exception in setMtu()" + e);
2656 }
2657 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002658
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002659 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002660 * Reads the network specific TCP buffer sizes from SystemProperties
2661 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2662 * wide use
2663 */
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002664 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002665 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002666 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002667
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002668 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002669 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002670
2671 // Setting to default values so we won't be stuck to previous values
2672 key = "net.tcp.buffersize.default";
2673 bufferSizes = SystemProperties.get(key);
2674 }
2675
2676 // Set values in kernel
2677 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002678 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002679 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002680 + "] which comes from [" + key + "]");
2681 }
2682 setBufferSize(bufferSizes);
2683 }
2684 }
2685
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002686 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002687 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2688 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2689 *
2690 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2691 * writeMin, writeInitial, writeMax"
2692 */
2693 private void setBufferSize(String bufferSizes) {
2694 try {
2695 String[] values = bufferSizes.split(",");
2696
2697 if (values.length == 6) {
2698 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002699 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2700 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2701 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2702 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2703 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2704 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002705 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002706 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002707 }
2708 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002709 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002710 }
2711 }
2712
Robert Greenwalt2034b912009-08-12 16:08:25 -07002713 /**
2714 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2715 * on the highest priority active net which this process requested.
2716 * If there aren't any, clear it out
2717 */
Mattias Falkd697aa22011-08-23 14:15:13 +02002718 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002719 {
Mattias Falkd697aa22011-08-23 14:15:13 +02002720 if (VDBG) log("reassessPidDns for pid " + pid);
2721 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002722 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002723 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002724 continue;
2725 }
2726 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002727 if (nt.getNetworkInfo().isConnected() &&
2728 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002729 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002730 if (p == null) continue;
Mattias Falkd697aa22011-08-23 14:15:13 +02002731 if (mNetRequestersPids[i].contains(myPid)) {
2732 try {
2733 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2734 } catch (Exception e) {
2735 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002736 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002737 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002738 }
2739 }
2740 }
2741 // nothing found - delete
Mattias Falkd697aa22011-08-23 14:15:13 +02002742 try {
2743 mNetd.clearDnsInterfaceForPid(pid);
2744 } catch (Exception e) {
2745 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002746 }
2747 }
2748
Mattias Falkd697aa22011-08-23 14:15:13 +02002749 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002750 /*
2751 * Tell the VMs to toss their DNS caches
2752 */
2753 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2754 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002755 /*
2756 * Connectivity events can happen before boot has completed ...
2757 */
2758 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002759 final long ident = Binder.clearCallingIdentity();
2760 try {
2761 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2762 } finally {
2763 Binder.restoreCallingIdentity(ident);
2764 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002765 }
2766
Chia-chi Yehcc844502011-07-14 18:01:57 -07002767 // Caller must grab mDnsLock.
Mattias Falkd697aa22011-08-23 14:15:13 +02002768 private void updateDnsLocked(String network, String iface,
Chad Brubaker73652d02013-07-23 17:13:36 -07002769 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002770 int last = 0;
2771 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002772 dnses = new ArrayList();
2773 dnses.add(mDefaultDns);
2774 if (DBG) {
2775 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002776 }
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002777 }
2778
Mattias Falkd697aa22011-08-23 14:15:13 +02002779 try {
2780 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker73652d02013-07-23 17:13:36 -07002781 if (defaultDns) {
2782 mNetd.setDefaultInterfaceForDns(iface);
2783 }
2784
Robert Greenwalte41e3b32013-02-11 15:25:10 -08002785 for (InetAddress dns : dnses) {
2786 ++last;
2787 String key = "net.dns" + last;
2788 String value = dns.getHostAddress();
2789 SystemProperties.set(key, value);
2790 }
2791 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2792 String key = "net.dns" + i;
2793 SystemProperties.set(key, "");
2794 }
2795 mNumDnsEntries = last;
Mattias Falkd697aa22011-08-23 14:15:13 +02002796 } catch (Exception e) {
Robert Greenwaltb87ab962013-09-24 11:05:57 -07002797 loge("exception setting default dns interface: " + e);
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002798 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002799 }
2800
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002801 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002802 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002803 NetworkStateTracker nt = mNetTrackers[netType];
2804 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002805 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002806 if (p == null) return;
2807 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002808 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002809 String network = nt.getNetworkInfo().getTypeName();
2810 synchronized (mDnsLock) {
Chad Brubaker5fdc1462013-07-23 17:44:41 -07002811 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002812 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002813 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002814 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002815 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltcd277852012-11-09 10:52:27 -08002816 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002817 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002818 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002819 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002820 // set per-pid dns for attached secondary nets
Mattias Falkd697aa22011-08-23 14:15:13 +02002821 List<Integer> pids = mNetRequestersPids[netType];
2822 for (Integer pid : pids) {
2823 try {
2824 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2825 } catch (Exception e) {
2826 Slog.e(TAG, "exception setting interface for pid: " + e);
2827 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002828 }
2829 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002830 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002831 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002832 }
2833
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002834 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002835 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2836 NETWORK_RESTORE_DELAY_PROP_NAME);
2837 if(restoreDefaultNetworkDelayStr != null &&
2838 restoreDefaultNetworkDelayStr.length() != 0) {
2839 try {
2840 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2841 } catch (NumberFormatException e) {
2842 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002843 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002844 // if the system property isn't set, use the value for the apn type
2845 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2846
2847 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2848 (mNetConfigs[networkType] != null)) {
2849 ret = mNetConfigs[networkType].restoreTime;
2850 }
2851 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002852 }
2853
2854 @Override
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002855 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2856 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002857 if (mContext.checkCallingOrSelfPermission(
2858 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002859 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002860 pw.println("Permission Denial: can't dump ConnectivityService " +
2861 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2862 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002863 return;
2864 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002865
2866 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002867 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002868 for (int i = 0; i < mNetTrackers.length; i++) {
2869 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002870 if (nst != null) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002871 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2872 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002873 if (nst.getNetworkInfo().isConnected()) {
2874 pw.println("Active network: " + nst.getNetworkInfo().
2875 getTypeName());
2876 }
2877 pw.println(nst.getNetworkInfo());
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002878 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002879 pw.println(nst);
2880 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002881 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002882 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002883 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002884
2885 pw.println("Network Requester Pids:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002886 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002887 for (int net : mPriorityList) {
2888 String pidString = net + ": ";
Mattias Falkd697aa22011-08-23 14:15:13 +02002889 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002890 pidString = pidString + pid.toString() + ", ";
2891 }
2892 pw.println(pidString);
2893 }
2894 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002895 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002896
2897 pw.println("FeatureUsers:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002898 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002899 for (Object requester : mFeatureUsers) {
2900 pw.println(requester.toString());
2901 }
2902 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002903 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002904
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002905 synchronized (this) {
2906 pw.println("NetworkTranstionWakeLock is currently " +
2907 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2908 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2909 }
2910 pw.println();
2911
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002912 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002913
2914 if (mInetLog != null) {
2915 pw.println();
2916 pw.println("Inet condition reports:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002917 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002918 for(int i = 0; i < mInetLog.size(); i++) {
2919 pw.println(mInetLog.get(i));
2920 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002921 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002922 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002923 }
2924
Robert Greenwalt2034b912009-08-12 16:08:25 -07002925 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002926 private class NetworkStateTrackerHandler extends Handler {
2927 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002928 super(looper);
2929 }
2930
The Android Open Source Project28527d22009-03-03 19:31:44 -08002931 @Override
2932 public void handleMessage(Message msg) {
2933 NetworkInfo info;
2934 switch (msg.what) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002935 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002936 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002937 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002938
Wink Savillea7d56572011-09-21 11:05:43 -07002939 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Savilleb1a32022013-09-05 12:02:25 -07002940 (state == NetworkInfo.State.DISCONNECTED) ||
2941 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillea7d56572011-09-21 11:05:43 -07002942 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002943 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002944 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002945 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002946
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002947 // Since mobile has the notion of a network/apn that can be used for
2948 // provisioning we need to check every time we're connected as
2949 // CaptiveProtalTracker won't detected it because DCT doesn't report it
2950 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2951 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2952 // is received by MDST and sent here as EVENT_STATE_CHANGED.
2953 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Savillef0e9c7f2013-07-16 17:16:37 -07002954 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2955 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Saville11fa4722013-09-14 09:04:53 -07002956 && (((state == NetworkInfo.State.CONNECTED)
2957 && (info.getType() == ConnectivityManager.TYPE_MOBILE))
2958 || info.isConnectedToProvisioningNetwork())) {
2959 log("ConnectivityChange checkMobileProvisioning for"
2960 + " TYPE_MOBILE or ProvisioningNetwork");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002961 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Savillef0e9c7f2013-07-16 17:16:37 -07002962 }
2963
Jeff Sharkey876ddc92012-11-09 15:57:02 -08002964 EventLogTags.writeConnectivityStateChanged(
2965 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002966
2967 if (info.getDetailedState() ==
2968 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002969 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002970 } else if (info.getDetailedState() ==
2971 DetailedState.CAPTIVE_PORTAL_CHECK) {
2972 handleCaptivePortalTrackerCheck(info);
Wink Savilleb1a32022013-09-05 12:02:25 -07002973 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002974 /**
2975 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2976 * for now its an in between network, its a network that
2977 * is actually a default network but we don't want it to be
2978 * announced as such to keep background applications from
2979 * trying to use it. It turns out that some still try so we
2980 * take the additional step of clearing any default routes
2981 * to the link that may have incorrectly setup by the lower
2982 * levels.
2983 */
2984 LinkProperties lp = getLinkProperties(info.getType());
2985 if (DBG) {
2986 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2987 }
2988
2989 // Clear any default routes setup by the radio so
2990 // any activity by applications trying to use this
2991 // connection will fail until the provisioning network
2992 // is enabled.
2993 for (RouteInfo r : lp.getRoutes()) {
2994 removeRoute(lp, r, TO_DEFAULT_TABLE);
2995 }
Robert Greenwalt12c44552009-12-07 11:33:18 -08002996 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002997 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002998 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002999 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003000 // the logic here is, handle SUSPENDED the same as
3001 // DISCONNECTED. The only difference being we are
3002 // broadcasting an intent with NetworkInfo that's
3003 // suspended. This allows the applications an
3004 // opportunity to handle DISCONNECTED and SUSPENDED
3005 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08003006 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08003007 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003008 handleConnect(info);
3009 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003010 if (mLockdownTracker != null) {
3011 mLockdownTracker.onNetworkInfoChanged(info);
3012 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003013 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003014 }
3015 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07003016 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05003017 // TODO: Temporary allowing network configuration
3018 // change not resetting sockets.
3019 // @see bug/4455071
3020 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003021 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003022 }
3023 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07003024 info = (NetworkInfo) msg.obj;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003025 int type = info.getType();
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07003026 updateNetworkSettings(mNetTrackers[type]);
3027 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003028 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003029 }
3030 }
3031 }
3032
3033 private class InternalHandler extends Handler {
3034 public InternalHandler(Looper looper) {
3035 super(looper);
3036 }
3037
3038 @Override
3039 public void handleMessage(Message msg) {
3040 NetworkInfo info;
3041 switch (msg.what) {
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003042 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003043 String causedBy = null;
3044 synchronized (ConnectivityService.this) {
3045 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3046 mNetTransitionWakeLock.isHeld()) {
3047 mNetTransitionWakeLock.release();
3048 causedBy = mNetTransitionWakeLockCausedBy;
3049 }
3050 }
3051 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003052 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003053 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07003054 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003055 }
3056 case EVENT_RESTORE_DEFAULT_NETWORK: {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003057 FeatureUser u = (FeatureUser)msg.obj;
3058 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003059 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003060 }
3061 case EVENT_INET_CONDITION_CHANGE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003062 int netType = msg.arg1;
3063 int condition = msg.arg2;
3064 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003065 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003066 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003067 case EVENT_INET_CONDITION_HOLD_END: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003068 int netType = msg.arg1;
3069 int sequence = msg.arg2;
Wink Saville151eaa62013-01-31 00:30:13 +00003070 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07003071 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003072 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003073 case EVENT_SET_NETWORK_PREFERENCE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003074 int preference = msg.arg1;
3075 handleSetNetworkPreference(preference);
3076 break;
3077 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003078 case EVENT_SET_MOBILE_DATA: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003079 boolean enabled = (msg.arg1 == ENABLED);
3080 handleSetMobileData(enabled);
3081 break;
3082 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003083 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003084 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07003085 break;
3086 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003087 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwalt34848c02011-03-25 13:09:25 -07003088 boolean met = (msg.arg1 == ENABLED);
3089 handleSetDependencyMet(msg.arg2, met);
3090 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003091 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003092 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville4f0de1e2011-08-04 15:01:58 -07003093 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07003094 sendStickyBroadcast(intent);
3095 break;
3096 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07003097 case EVENT_SET_POLICY_DATA_ENABLE: {
3098 final int networkType = msg.arg1;
3099 final boolean enabled = msg.arg2 == ENABLED;
3100 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003101 break;
3102 }
3103 case EVENT_VPN_STATE_CHANGED: {
3104 if (mLockdownTracker != null) {
3105 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3106 }
3107 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07003108 }
Wink Saville32506bc2013-06-29 21:10:57 -07003109 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3110 int tag = mEnableFailFastMobileDataTag.get();
3111 if (msg.arg1 == tag) {
3112 MobileDataStateTracker mobileDst =
3113 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3114 if (mobileDst != null) {
3115 mobileDst.setEnableFailFastMobileData(msg.arg2);
3116 }
3117 } else {
3118 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3119 + " != tag:" + tag);
3120 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003121 break;
Wink Saville32506bc2013-06-29 21:10:57 -07003122 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003123 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07003124 handleNetworkSamplingTimeout();
3125 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003126 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003127 }
3128 }
3129 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003130
3131 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003132 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003133 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003134
3135 if (isTetheringSupported()) {
3136 return mTethering.tether(iface);
3137 } else {
3138 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3139 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003140 }
3141
3142 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003143 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003144 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003145
3146 if (isTetheringSupported()) {
3147 return mTethering.untether(iface);
3148 } else {
3149 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3150 }
3151 }
3152
3153 // javadoc from interface
3154 public int getLastTetherError(String iface) {
3155 enforceTetherAccessPermission();
3156
3157 if (isTetheringSupported()) {
3158 return mTethering.getLastTetherError(iface);
3159 } else {
3160 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3161 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003162 }
3163
3164 // TODO - proper iface API for selection by property, inspection, etc
3165 public String[] getTetherableUsbRegexs() {
3166 enforceTetherAccessPermission();
3167 if (isTetheringSupported()) {
3168 return mTethering.getTetherableUsbRegexs();
3169 } else {
3170 return new String[0];
3171 }
3172 }
3173
3174 public String[] getTetherableWifiRegexs() {
3175 enforceTetherAccessPermission();
3176 if (isTetheringSupported()) {
3177 return mTethering.getTetherableWifiRegexs();
3178 } else {
3179 return new String[0];
3180 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003181 }
3182
Danica Chang96567052010-08-11 14:54:43 -07003183 public String[] getTetherableBluetoothRegexs() {
3184 enforceTetherAccessPermission();
3185 if (isTetheringSupported()) {
3186 return mTethering.getTetherableBluetoothRegexs();
3187 } else {
3188 return new String[0];
3189 }
3190 }
3191
Mike Lockwooded4a1742011-07-19 13:04:47 -07003192 public int setUsbTethering(boolean enable) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003193 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07003194 if (isTetheringSupported()) {
3195 return mTethering.setUsbTethering(enable);
3196 } else {
3197 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3198 }
3199 }
3200
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003201 // TODO - move iface listing, queries, etc to new module
3202 // javadoc from interface
3203 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003204 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003205 return mTethering.getTetherableIfaces();
3206 }
3207
3208 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003209 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003210 return mTethering.getTetheredIfaces();
3211 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003212
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003213 public String[] getTetheringErroredIfaces() {
3214 enforceTetherAccessPermission();
3215 return mTethering.getErroredIfaces();
3216 }
3217
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003218 // if ro.tether.denied = true we default to no tethering
3219 // gservices could set the secure setting to 1 though to enable it on a build where it
3220 // had previously been turned off.
3221 public boolean isTetheringSupported() {
3222 enforceTetherAccessPermission();
3223 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownc67cf562012-09-25 15:03:20 -07003224 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3225 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt368095f2013-07-18 14:24:42 -07003226 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3227 mTethering.getTetherableWifiRegexs().length != 0 ||
3228 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3229 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003230 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003231
3232 // An API NetworkStateTrackers can call when they lose their network.
3233 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3234 // whichever happens first. The timer is started by the first caller and not
3235 // restarted by subsequent callers.
3236 public void requestNetworkTransitionWakelock(String forWhom) {
3237 enforceConnectivityInternalPermission();
3238 synchronized (this) {
3239 if (mNetTransitionWakeLock.isHeld()) return;
3240 mNetTransitionWakeLockSerialNumber++;
3241 mNetTransitionWakeLock.acquire();
3242 mNetTransitionWakeLockCausedBy = forWhom;
3243 }
3244 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003245 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003246 mNetTransitionWakeLockSerialNumber, 0),
3247 mNetTransitionWakeLockTimeout);
3248 return;
3249 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003250
Robert Greenwalt986c7412010-09-08 15:24:47 -07003251 // 100 percent is full good, 0 is full bad.
3252 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003253 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003254 mContext.enforceCallingOrSelfPermission(
3255 android.Manifest.permission.STATUS_BAR,
3256 "ConnectivityService");
3257
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003258 if (DBG) {
3259 int pid = getCallingPid();
3260 int uid = getCallingUid();
3261 String s = pid + "(" + uid + ") reports inet is " +
3262 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3263 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3264 mInetLog.add(s);
3265 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3266 mInetLog.remove(0);
3267 }
3268 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003269 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003270 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3271 }
3272
3273 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003274 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003275 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003276 return;
3277 }
3278 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003279 if (DBG) log("handleInetConditionChange: net=" + netType +
3280 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003281 return;
3282 }
Wink Savillea7d56572011-09-21 11:05:43 -07003283 if (VDBG) {
3284 log("handleInetConditionChange: net=" +
3285 netType + ", condition=" + condition +
Wink Saville151eaa62013-01-31 00:30:13 +00003286 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003287 }
Wink Saville151eaa62013-01-31 00:30:13 +00003288 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003289 int delay;
3290 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003291 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003292 // setup a new hold to debounce this
Wink Saville151eaa62013-01-31 00:30:13 +00003293 if (mDefaultInetCondition > 50) {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003294 delay = Settings.Global.getInt(mContext.getContentResolver(),
3295 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003296 } else {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003297 delay = Settings.Global.getInt(mContext.getContentResolver(),
3298 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003299 }
3300 mInetConditionChangeInFlight = true;
3301 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville151eaa62013-01-31 00:30:13 +00003302 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003303 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003304 // we've set the new condition, when this hold ends that will get picked up
3305 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003306 }
3307 }
3308
Wink Saville151eaa62013-01-31 00:30:13 +00003309 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003310 if (DBG) {
Wink Saville151eaa62013-01-31 00:30:13 +00003311 log("handleInetConditionHoldEnd: net=" + netType +
3312 ", condition=" + mDefaultInetCondition +
3313 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003314 }
3315 mInetConditionChangeInFlight = false;
3316
3317 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003318 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003319 return;
3320 }
3321 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003322 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003323 return;
3324 }
Wink Saville151eaa62013-01-31 00:30:13 +00003325 // TODO: Figure out why this optimization sometimes causes a
3326 // change in mDefaultInetCondition to be missed and the
3327 // UI to not be updated.
3328 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3329 // if (DBG) log("no change in condition - aborting");
3330 // return;
3331 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003332 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3333 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003334 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003335 return;
3336 }
Wink Saville151eaa62013-01-31 00:30:13 +00003337 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003338 sendInetConditionBroadcast(networkInfo);
3339 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003340 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003341
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003342 public ProxyProperties getProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003343 // this information is already available as a world read/writable jvm property
3344 // so this API change wouldn't have a benifit. It also breaks the passing
3345 // of proxy info to all the JVMs.
3346 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003347 synchronized (mProxyLock) {
Jason Monka5bf2842013-07-03 17:04:33 -04003348 ProxyProperties ret = mGlobalProxy;
3349 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3350 return ret;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003351 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003352 }
3353
3354 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003355 enforceConnectivityInternalPermission();
Jason Monka5bf2842013-07-03 17:04:33 -04003356
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003357 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003358 if (proxyProperties == mGlobalProxy) return;
3359 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3360 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3361
3362 String host = "";
3363 int port = 0;
3364 String exclList = "";
Jason Monka5bf2842013-07-03 17:04:33 -04003365 String pacFileUrl = "";
3366 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3367 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003368 mGlobalProxy = new ProxyProperties(proxyProperties);
3369 host = mGlobalProxy.getHost();
3370 port = mGlobalProxy.getPort();
3371 exclList = mGlobalProxy.getExclusionList();
Jason Monka5bf2842013-07-03 17:04:33 -04003372 if (proxyProperties.getPacFileUrl() != null) {
3373 pacFileUrl = proxyProperties.getPacFileUrl();
3374 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003375 } else {
3376 mGlobalProxy = null;
3377 }
3378 ContentResolver res = mContext.getContentResolver();
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003379 final long token = Binder.clearCallingIdentity();
3380 try {
3381 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3382 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3383 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3384 exclList);
Jason Monka5bf2842013-07-03 17:04:33 -04003385 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003386 } finally {
3387 Binder.restoreCallingIdentity(token);
3388 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003389 }
3390
3391 if (mGlobalProxy == null) {
3392 proxyProperties = mDefaultProxy;
3393 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003394 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003395 }
3396
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003397 private void loadGlobalProxy() {
3398 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003399 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3400 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3401 String exclList = Settings.Global.getString(res,
3402 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monka5bf2842013-07-03 17:04:33 -04003403 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3404 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3405 ProxyProperties proxyProperties;
3406 if (!TextUtils.isEmpty(pacFileUrl)) {
3407 proxyProperties = new ProxyProperties(pacFileUrl);
3408 } else {
3409 proxyProperties = new ProxyProperties(host, port, exclList);
3410 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003411 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003412 mGlobalProxy = proxyProperties;
3413 }
3414 }
3415 }
3416
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003417 public ProxyProperties getGlobalProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003418 // this information is already available as a world read/writable jvm property
3419 // so this API change wouldn't have a benifit. It also breaks the passing
3420 // of proxy info to all the JVMs.
3421 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003422 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003423 return mGlobalProxy;
3424 }
3425 }
3426
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003427 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04003428 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3429 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003430 proxy = null;
3431 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003432 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003433 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003434 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003435 mDefaultProxy = proxy;
3436
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003437 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003438 if (!mDefaultProxyDisabled) {
3439 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003440 }
3441 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003442 }
3443
3444 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003445 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3446 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003447 if (!TextUtils.isEmpty(proxy)) {
3448 String data[] = proxy.split(":");
Andreas Huber23bff232013-05-28 15:17:37 -07003449 if (data.length == 0) {
3450 return;
3451 }
3452
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003453 String proxyHost = data[0];
3454 int proxyPort = 8080;
3455 if (data.length > 1) {
3456 try {
3457 proxyPort = Integer.parseInt(data[1]);
3458 } catch (NumberFormatException e) {
3459 return;
3460 }
3461 }
3462 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3463 setGlobalProxy(p);
3464 }
3465 }
3466
3467 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003468 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monk0a9cc502013-08-23 19:21:25 -04003469 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt78f28112011-08-02 17:18:41 -07003470 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003471 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003472 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3473 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003474 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003475 final long ident = Binder.clearCallingIdentity();
3476 try {
3477 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3478 } finally {
3479 Binder.restoreCallingIdentity(ident);
3480 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003481 }
3482
3483 private static class SettingsObserver extends ContentObserver {
3484 private int mWhat;
3485 private Handler mHandler;
3486 SettingsObserver(Handler handler, int what) {
3487 super(handler);
3488 mHandler = handler;
3489 mWhat = what;
3490 }
3491
3492 void observe(Context context) {
3493 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003494 resolver.registerContentObserver(Settings.Global.getUriFor(
3495 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003496 }
3497
3498 @Override
3499 public void onChange(boolean selfChange) {
3500 mHandler.obtainMessage(mWhat).sendToTarget();
3501 }
3502 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003503
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003504 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003505 Slog.d(TAG, s);
3506 }
3507
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003508 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003509 Slog.e(TAG, s);
3510 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003511
repo syncf5de5572011-07-29 23:55:49 -07003512 int convertFeatureToNetworkType(int networkType, String feature) {
3513 int usedNetworkType = networkType;
3514
3515 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3516 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3517 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3518 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3519 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3520 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3521 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3522 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3523 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3524 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3525 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3526 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3527 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3528 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3529 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3530 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3531 } else {
3532 Slog.e(TAG, "Can't match any mobile netTracker!");
3533 }
3534 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3535 if (TextUtils.equals(feature, "p2p")) {
3536 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3537 } else {
3538 Slog.e(TAG, "Can't match any wifi netTracker!");
3539 }
3540 } else {
3541 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003542 }
repo syncf5de5572011-07-29 23:55:49 -07003543 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003544 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003545
3546 private static <T> T checkNotNull(T value, String message) {
3547 if (value == null) {
3548 throw new NullPointerException(message);
3549 }
3550 return value;
3551 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003552
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003553 /**
3554 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003555 * VpnBuilder and not available in ConnectivityManager. Permissions
3556 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003557 * @hide
3558 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003559 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003560 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003561 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003562 try {
3563 int type = mActiveDefaultNetwork;
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003564 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt15a41532012-08-21 19:27:00 -07003565 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003566 synchronized(mVpns) {
3567 mVpns.get(user).protect(socket,
3568 mNetTrackers[type].getLinkProperties().getInterfaceName());
3569 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003570 return true;
3571 }
3572 } catch (Exception e) {
3573 // ignore
3574 } finally {
3575 try {
3576 socket.close();
3577 } catch (Exception e) {
3578 // ignore
3579 }
3580 }
3581 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003582 }
3583
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003584 /**
3585 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003586 * and not available in ConnectivityManager. Permissions are checked
3587 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003588 * @hide
3589 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003590 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003591 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003592 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003593 int user = UserHandle.getUserId(Binder.getCallingUid());
3594 synchronized(mVpns) {
3595 return mVpns.get(user).prepare(oldPackage, newPackage);
3596 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003597 }
3598
Chad Brubaker11f22252013-07-11 13:29:30 -07003599 @Override
3600 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3601 enforceMarkNetworkSocketPermission();
3602 final long token = Binder.clearCallingIdentity();
3603 try {
3604 int mark = mNetd.getMarkForUid(uid);
3605 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3606 if (mark == -1) {
3607 mark = 0;
3608 }
3609 NetworkUtils.markSocket(socket.getFd(), mark);
3610 } catch (RemoteException e) {
3611 } finally {
3612 Binder.restoreCallingIdentity(token);
3613 }
3614 }
3615
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003616 /**
3617 * Configure a TUN interface and return its file descriptor. Parameters
3618 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003619 * and not available in ConnectivityManager. Permissions are checked in
3620 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003621 * @hide
3622 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003623 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003624 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003625 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003626 int user = UserHandle.getUserId(Binder.getCallingUid());
3627 synchronized(mVpns) {
3628 return mVpns.get(user).establish(config);
3629 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003630 }
3631
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003632 /**
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003633 * Start legacy VPN, controlling native daemons as needed. Creates a
3634 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003635 */
3636 @Override
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003637 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003638 throwIfLockdownEnabled();
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003639 final LinkProperties egress = getActiveLinkProperties();
3640 if (egress == null) {
3641 throw new IllegalStateException("Missing active network connection");
3642 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003643 int user = UserHandle.getUserId(Binder.getCallingUid());
3644 synchronized(mVpns) {
3645 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3646 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003647 }
3648
3649 /**
3650 * Return the information of the ongoing legacy VPN. This method is used
3651 * by VpnSettings and not available in ConnectivityManager. Permissions
3652 * are checked in Vpn class.
3653 * @hide
3654 */
3655 @Override
3656 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003657 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003658 int user = UserHandle.getUserId(Binder.getCallingUid());
3659 synchronized(mVpns) {
3660 return mVpns.get(user).getLegacyVpnInfo();
3661 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003662 }
3663
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003664 /**
Chad Brubaker94f3c8c2013-07-16 18:59:12 -07003665 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3666 * not available in ConnectivityManager.
3667 * Permissions are checked in Vpn class.
3668 * @hide
3669 */
3670 @Override
3671 public VpnConfig getVpnConfig() {
3672 int user = UserHandle.getUserId(Binder.getCallingUid());
3673 synchronized(mVpns) {
3674 return mVpns.get(user).getVpnConfig();
3675 }
3676 }
3677
3678 /**
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003679 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3680 * through NetworkStateTracker since it works differently. For example, it
3681 * needs to override DNS servers but never takes the default routes. It
3682 * relies on another data network, and it could keep existing connections
3683 * alive after reconnecting, switching between networks, or even resuming
3684 * from deep sleep. Calls from applications should be done synchronously
3685 * to avoid race conditions. As these are all hidden APIs, refactoring can
3686 * be done whenever a better abstraction is developed.
3687 */
3688 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003689 private VpnCallback() {
3690 }
3691
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003692 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003693 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003694 }
3695
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003696 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07003697 if (dnsServers == null) {
3698 restore();
3699 return;
3700 }
3701
3702 // Convert DNS servers into addresses.
3703 List<InetAddress> addresses = new ArrayList<InetAddress>();
3704 for (String address : dnsServers) {
3705 // Double check the addresses and remove invalid ones.
3706 try {
3707 addresses.add(InetAddress.parseNumericAddress(address));
3708 } catch (Exception e) {
3709 // ignore
3710 }
3711 }
3712 if (addresses.isEmpty()) {
3713 restore();
3714 return;
3715 }
3716
3717 // Concatenate search domains into a string.
3718 StringBuilder buffer = new StringBuilder();
3719 if (searchDomains != null) {
3720 for (String domain : searchDomains) {
3721 buffer.append(domain).append(' ');
3722 }
3723 }
3724 String domains = buffer.toString().trim();
3725
3726 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003727 synchronized (mDnsLock) {
Chad Brubaker73652d02013-07-23 17:13:36 -07003728 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003729 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003730
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003731 // Temporarily disable the default proxy (not global).
3732 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003733 mDefaultProxyDisabled = true;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003734 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003735 sendProxyBroadcast(null);
3736 }
3737 }
3738
3739 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003740 }
3741
Chia-chi Yehcc844502011-07-14 18:01:57 -07003742 public void restore() {
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003743 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003744 mDefaultProxyDisabled = false;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003745 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003746 sendProxyBroadcast(mDefaultProxy);
3747 }
3748 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003749 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003750
3751 public void protect(ParcelFileDescriptor socket) {
3752 try {
3753 final int mark = mNetd.getMarkForProtect();
3754 NetworkUtils.markSocket(socket.getFd(), mark);
3755 } catch (RemoteException e) {
3756 }
3757 }
3758
3759 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3760 for (RouteInfo route : routes) {
3761 try {
3762 mNetd.setMarkedForwardingRoute(interfaze, route);
3763 } catch (RemoteException e) {
3764 }
3765 }
3766 }
3767
3768 public void setMarkedForwarding(String interfaze) {
3769 try {
3770 mNetd.setMarkedForwarding(interfaze);
3771 } catch (RemoteException e) {
3772 }
3773 }
3774
3775 public void clearMarkedForwarding(String interfaze) {
3776 try {
3777 mNetd.clearMarkedForwarding(interfaze);
3778 } catch (RemoteException e) {
3779 }
3780 }
3781
Robert Greenwaltb87ab962013-09-24 11:05:57 -07003782 public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003783 int uidStart = uid * UserHandle.PER_USER_RANGE;
3784 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwaltb87ab962013-09-24 11:05:57 -07003785 addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003786 }
3787
Robert Greenwaltb87ab962013-09-24 11:05:57 -07003788 public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003789 int uidStart = uid * UserHandle.PER_USER_RANGE;
3790 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwaltb87ab962013-09-24 11:05:57 -07003791 clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003792 }
3793
Robert Greenwaltb87ab962013-09-24 11:05:57 -07003794 public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
3795 boolean forwardDns) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003796 try {
3797 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
Robert Greenwaltb87ab962013-09-24 11:05:57 -07003798 if (forwardDns) mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003799 } catch (RemoteException e) {
3800 }
3801
3802 }
3803
Robert Greenwaltb87ab962013-09-24 11:05:57 -07003804 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
3805 boolean forwardDns) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003806 try {
3807 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
Robert Greenwaltb87ab962013-09-24 11:05:57 -07003808 if (forwardDns) mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003809 } catch (RemoteException e) {
3810 }
3811
3812 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003813 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003814
3815 @Override
3816 public boolean updateLockdownVpn() {
Jeff Sharkey760c6202013-01-31 17:22:26 -08003817 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3818 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3819 return false;
3820 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003821
3822 // Tear down existing lockdown if profile was removed
3823 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3824 if (mLockdownEnabled) {
Kenny Root0ded63c2013-02-14 10:18:38 -08003825 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003826 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3827 return false;
3828 }
3829
3830 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3831 final VpnProfile profile = VpnProfile.decode(
3832 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003833 int user = UserHandle.getUserId(Binder.getCallingUid());
3834 synchronized(mVpns) {
3835 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3836 profile));
3837 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003838 } else {
3839 setLockdownTracker(null);
3840 }
3841
3842 return true;
3843 }
3844
3845 /**
3846 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3847 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3848 */
3849 private void setLockdownTracker(LockdownVpnTracker tracker) {
3850 // Shutdown any existing tracker
3851 final LockdownVpnTracker existing = mLockdownTracker;
3852 mLockdownTracker = null;
3853 if (existing != null) {
3854 existing.shutdown();
3855 }
3856
3857 try {
3858 if (tracker != null) {
3859 mNetd.setFirewallEnabled(true);
Jeff Sharkeydb44d2c2013-02-28 16:57:58 -08003860 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003861 mLockdownTracker = tracker;
3862 mLockdownTracker.init();
3863 } else {
3864 mNetd.setFirewallEnabled(false);
3865 }
3866 } catch (RemoteException e) {
3867 // ignored; NMS lives inside system_server
3868 }
3869 }
3870
3871 private void throwIfLockdownEnabled() {
3872 if (mLockdownEnabled) {
3873 throw new IllegalStateException("Unavailable in lockdown mode");
3874 }
3875 }
Robert Greenwalt15a41532012-08-21 19:27:00 -07003876
3877 public void supplyMessenger(int networkType, Messenger messenger) {
3878 enforceConnectivityInternalPermission();
3879
3880 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3881 mNetTrackers[networkType].supplyMessenger(messenger);
3882 }
3883 }
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -07003884
3885 public int findConnectionTypeForIface(String iface) {
3886 enforceConnectivityInternalPermission();
3887
3888 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3889 for (NetworkStateTracker tracker : mNetTrackers) {
3890 if (tracker != null) {
3891 LinkProperties lp = tracker.getLinkProperties();
3892 if (lp != null && iface.equals(lp.getInterfaceName())) {
3893 return tracker.getNetworkInfo().getType();
3894 }
3895 }
3896 }
3897 return ConnectivityManager.TYPE_NONE;
3898 }
Wink Saville32506bc2013-06-29 21:10:57 -07003899
3900 /**
3901 * Have mobile data fail fast if enabled.
3902 *
3903 * @param enabled DctConstants.ENABLED/DISABLED
3904 */
3905 private void setEnableFailFastMobileData(int enabled) {
3906 int tag;
3907
3908 if (enabled == DctConstants.ENABLED) {
3909 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3910 } else {
3911 tag = mEnableFailFastMobileDataTag.get();
3912 }
3913 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3914 enabled));
3915 }
3916
Wink Savilled23fa092013-08-16 17:17:28 -07003917 private boolean isMobileDataStateTrackerReady() {
3918 MobileDataStateTracker mdst =
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003919 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savilled23fa092013-08-16 17:17:28 -07003920 return (mdst != null) && (mdst.isReady());
3921 }
3922
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003923 /**
3924 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3925 */
3926
3927 /**
3928 * No connection was possible to the network.
Wink Saville9685cd12013-09-06 09:53:08 -07003929 * This is NOT a warm sim.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003930 */
Wink Saville9685cd12013-09-06 09:53:08 -07003931 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003932
3933 /**
3934 * A connection was made to the internet, all is well.
Wink Saville9685cd12013-09-06 09:53:08 -07003935 * This is NOT a warm sim.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003936 */
Wink Saville9685cd12013-09-06 09:53:08 -07003937 private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003938
3939 /**
3940 * A connection was made but no dns server was available to resolve a name to address.
Wink Saville9685cd12013-09-06 09:53:08 -07003941 * This is NOT a warm sim since provisioning network is supported.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003942 */
Wink Saville9685cd12013-09-06 09:53:08 -07003943 private static final int CMP_RESULT_CODE_NO_DNS = 2;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003944
3945 /**
3946 * A connection was made but could not open a TCP connection.
Wink Saville9685cd12013-09-06 09:53:08 -07003947 * This is NOT a warm sim since provisioning network is supported.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003948 */
Wink Saville9685cd12013-09-06 09:53:08 -07003949 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
3950
3951 /**
3952 * A connection was made but there was a redirection, we appear to be in walled garden.
3953 * This is an indication of a warm sim on a mobile network such as T-Mobile.
3954 */
3955 private static final int CMP_RESULT_CODE_REDIRECTED = 4;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003956
3957 /**
3958 * The mobile network is a provisioning network.
Wink Saville9685cd12013-09-06 09:53:08 -07003959 * This is an indication of a warm sim on a mobile network such as AT&T.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003960 */
Wink Saville9685cd12013-09-06 09:53:08 -07003961 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003962
Wink Saville9685cd12013-09-06 09:53:08 -07003963 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003964
Wink Saville32506bc2013-06-29 21:10:57 -07003965 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003966 public int checkMobileProvisioning(int suggestedTimeOutMs) {
3967 int timeOutMs = -1;
3968 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
3969 enforceConnectivityInternalPermission();
Wink Savilled469c472013-07-02 10:55:14 -07003970
Wink Saville32506bc2013-06-29 21:10:57 -07003971 final long token = Binder.clearCallingIdentity();
3972 try {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003973 timeOutMs = suggestedTimeOutMs;
3974 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3975 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3976 }
3977
3978 // Check that mobile networks are supported
3979 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3980 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3981 if (DBG) log("checkMobileProvisioning: X no mobile network");
3982 return timeOutMs;
3983 }
3984
3985 // If we're already checking don't do it again
3986 // TODO: Add a queue of results...
3987 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
3988 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
3989 return timeOutMs;
3990 }
3991
Wink Saville76f49d32013-10-03 08:34:46 -07003992 // Start off with mobile notification off
3993 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003994
Wink Saville32506bc2013-06-29 21:10:57 -07003995 CheckMp checkMp = new CheckMp(mContext, this);
3996 CheckMp.CallBack cb = new CheckMp.CallBack() {
3997 @Override
3998 void onComplete(Integer result) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003999 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Saville32506bc2013-06-29 21:10:57 -07004000 NetworkInfo ni =
4001 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4002 switch(result) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004003 case CMP_RESULT_CODE_CONNECTABLE:
Wink Saville9685cd12013-09-06 09:53:08 -07004004 case CMP_RESULT_CODE_NO_CONNECTION:
4005 case CMP_RESULT_CODE_NO_DNS:
4006 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004007 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Saville32506bc2013-06-29 21:10:57 -07004008 break;
4009 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004010 case CMP_RESULT_CODE_REDIRECTED: {
4011 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalt39d56012013-07-16 12:06:09 -07004012 String url = getMobileProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004013 if (TextUtils.isEmpty(url)) {
Robert Greenwalt39d56012013-07-16 12:06:09 -07004014 url = getMobileRedirectedProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004015 }
4016 if (TextUtils.isEmpty(url) == false) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004017 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
Wink Saville76f49d32013-10-03 08:34:46 -07004018 setProvNotificationVisible(true,
4019 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004020 url);
Wink Saville32506bc2013-06-29 21:10:57 -07004021 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004022 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Saville32506bc2013-06-29 21:10:57 -07004023 }
4024 break;
4025 }
Wink Saville9685cd12013-09-06 09:53:08 -07004026 case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
Robert Greenwalt39d56012013-07-16 12:06:09 -07004027 String url = getMobileProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004028 if (TextUtils.isEmpty(url) == false) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004029 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
Wink Saville76f49d32013-10-03 08:34:46 -07004030 setProvNotificationVisible(true,
4031 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004032 url);
Wink Saville32506bc2013-06-29 21:10:57 -07004033 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004034 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Saville32506bc2013-06-29 21:10:57 -07004035 }
4036 break;
4037 }
4038 default: {
4039 loge("CheckMp.onComplete: ignore unexpected result=" + result);
4040 break;
4041 }
4042 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004043 mIsCheckingMobileProvisioning.set(false);
Wink Saville32506bc2013-06-29 21:10:57 -07004044 }
4045 };
4046 CheckMp.Params params =
4047 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004048 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Saville32506bc2013-06-29 21:10:57 -07004049 checkMp.execute(params);
4050 } finally {
4051 Binder.restoreCallingIdentity(token);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004052 if (DBG) log("checkMobileProvisioning: X");
Wink Saville32506bc2013-06-29 21:10:57 -07004053 }
4054 return timeOutMs;
4055 }
4056
4057 static class CheckMp extends
4058 AsyncTask<CheckMp.Params, Void, Integer> {
4059 private static final String CHECKMP_TAG = "CheckMp";
4060 public static final int MAX_TIMEOUT_MS = 60000;
4061 private static final int SOCKET_TIMEOUT_MS = 5000;
4062 private Context mContext;
4063 private ConnectivityService mCs;
4064 private TelephonyManager mTm;
4065 private Params mParams;
4066
4067 /**
4068 * Parameters for AsyncTask.execute
4069 */
4070 static class Params {
4071 private String mUrl;
4072 private long mTimeOutMs;
4073 private CallBack mCb;
4074
4075 Params(String url, long timeOutMs, CallBack cb) {
4076 mUrl = url;
4077 mTimeOutMs = timeOutMs;
4078 mCb = cb;
4079 }
4080
4081 @Override
4082 public String toString() {
4083 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4084 }
4085 }
4086
4087 /**
4088 * The call back object passed in Params. onComplete will be called
4089 * on the main thread.
4090 */
4091 abstract static class CallBack {
4092 // Called on the main thread.
4093 abstract void onComplete(Integer result);
4094 }
4095
4096 public CheckMp(Context context, ConnectivityService cs) {
4097 mContext = context;
4098 mCs = cs;
4099
4100 // Setup access to TelephonyService we'll be using.
4101 mTm = (TelephonyManager) mContext.getSystemService(
4102 Context.TELEPHONY_SERVICE);
4103 }
4104
4105 /**
4106 * Get the default url to use for the test.
4107 */
4108 public String getDefaultUrl() {
4109 // See http://go/clientsdns for usage approval
4110 String server = Settings.Global.getString(mContext.getContentResolver(),
4111 Settings.Global.CAPTIVE_PORTAL_SERVER);
4112 if (server == null) {
4113 server = "clients3.google.com";
4114 }
4115 return "http://" + server + "/generate_204";
4116 }
4117
4118 /**
4119 * Detect if its possible to connect to the http url. DNS based detection techniques
4120 * do not work at all hotspots. The best way to check is to perform a request to
4121 * a known address that fetches the data we expect.
4122 */
4123 private synchronized Integer isMobileOk(Params params) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004124 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004125 Uri orgUri = Uri.parse(params.mUrl);
4126 Random rand = new Random();
4127 mParams = params;
4128
Wink Saville69e2de02013-08-13 12:41:06 -07004129 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004130 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Savillee14346f2013-09-13 12:40:11 -07004131 log("isMobileOk: X not mobile capable result=" + result);
4132 return result;
4133 }
4134
4135 // See if we've already determined we've got a provisioning connection,
4136 // if so we don't need to do anything active.
4137 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4138 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4139 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4140 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4141
4142 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4143 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4144 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4145 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4146
4147 if (isDefaultProvisioning || isHipriProvisioning) {
4148 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4149 log("isMobileOk: X default || hipri is provisioning result=" + result);
Wink Saville69e2de02013-08-13 12:41:06 -07004150 return result;
4151 }
Wink Saville32506bc2013-06-29 21:10:57 -07004152
Wink Saville69e2de02013-08-13 12:41:06 -07004153 try {
Wink Saville32506bc2013-06-29 21:10:57 -07004154 // Continue trying to connect until time has run out
4155 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville15f12922013-08-07 11:02:57 -07004156
Wink Savilled23fa092013-08-16 17:17:28 -07004157 if (!mCs.isMobileDataStateTrackerReady()) {
4158 // Wait for MobileDataStateTracker to be ready.
4159 if (DBG) log("isMobileOk: mdst is not ready");
4160 while(SystemClock.elapsedRealtime() < endTime) {
4161 if (mCs.isMobileDataStateTrackerReady()) {
4162 // Enable fail fast as we'll do retries here and use a
4163 // hipri connection so the default connection stays active.
4164 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4165 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4166 break;
4167 }
4168 sleep(1);
4169 }
4170 }
4171
4172 log("isMobileOk: start hipri url=" + params.mUrl);
4173
Wink Saville15f12922013-08-07 11:02:57 -07004174 // First wait until we can start using hipri
4175 Binder binder = new Binder();
4176 while(SystemClock.elapsedRealtime() < endTime) {
4177 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4178 Phone.FEATURE_ENABLE_HIPRI, binder);
4179 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4180 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4181 log("isMobileOk: hipri started");
4182 break;
4183 }
4184 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004185 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville15f12922013-08-07 11:02:57 -07004186 sleep(1);
4187 }
4188
4189 // Continue trying to connect until time has run out
Wink Saville32506bc2013-06-29 21:10:57 -07004190 while(SystemClock.elapsedRealtime() < endTime) {
4191 try {
4192 // Wait for hipri to connect.
4193 // TODO: Don't poll and handle situation where hipri fails
4194 // because default is retrying. See b/9569540
4195 NetworkInfo.State state = mCs
4196 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4197 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004198 if (true/*VDBG*/) {
Wink Savilled28eef42013-07-31 15:49:04 -07004199 log("isMobileOk: not connected ni=" +
Wink Saville32506bc2013-06-29 21:10:57 -07004200 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Savilled28eef42013-07-31 15:49:04 -07004201 }
Wink Saville32506bc2013-06-29 21:10:57 -07004202 sleep(1);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004203 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004204 continue;
4205 }
4206
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004207 // Hipri has started check if this is a provisioning url
4208 MobileDataStateTracker mdst = (MobileDataStateTracker)
4209 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4210 if (mdst.isProvisioningNetwork()) {
Wink Saville9685cd12013-09-06 09:53:08 -07004211 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
Wink Savillee14346f2013-09-13 12:40:11 -07004212 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004213 return result;
4214 } else {
4215 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4216 }
4217
Wink Saville32506bc2013-06-29 21:10:57 -07004218 // Get of the addresses associated with the url host. We need to use the
4219 // address otherwise HttpURLConnection object will use the name to get
4220 // the addresses and is will try every address but that will bypass the
4221 // route to host we setup and the connection could succeed as the default
4222 // interface might be connected to the internet via wifi or other interface.
4223 InetAddress[] addresses;
4224 try {
4225 addresses = InetAddress.getAllByName(orgUri.getHost());
4226 } catch (UnknownHostException e) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004227 result = CMP_RESULT_CODE_NO_DNS;
Wink Savillee14346f2013-09-13 12:40:11 -07004228 log("isMobileOk: X UnknownHostException result=" + result);
Wink Saville32506bc2013-06-29 21:10:57 -07004229 return result;
4230 }
4231 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4232
4233 // Get the type of addresses supported by this link
4234 LinkProperties lp = mCs.getLinkProperties(
4235 ConnectivityManager.TYPE_MOBILE_HIPRI);
Lorenzo Colitti09de4182013-08-08 11:00:12 +09004236 boolean linkHasIpv4 = lp.hasIPv4Address();
4237 boolean linkHasIpv6 = lp.hasIPv6Address();
Wink Saville32506bc2013-06-29 21:10:57 -07004238 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4239 + " linkHasIpv6=" + linkHasIpv6);
4240
4241 // Loop through at most 3 valid addresses or all of the address or until
4242 // we run out of time
4243 int loops = Math.min(3, addresses.length);
4244 for(int validAddr=0, addrTried=0;
4245 (validAddr < loops) && (addrTried < addresses.length)
4246 && (SystemClock.elapsedRealtime() < endTime);
4247 addrTried ++) {
4248
4249 // Choose the address at random but make sure its type is supported
Lorenzo Colitti9405bee2013-10-08 10:41:25 +09004250 // TODO: This doesn't work 100% of the time, because we may end up
4251 // trying the same invalid address more than once and ignoring one
4252 // of the valid addresses.
Wink Saville32506bc2013-06-29 21:10:57 -07004253 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
4254 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
4255 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
4256 // Valid address, so use it
4257 validAddr += 1;
4258 } else {
4259 // Invalid address so try next address
4260 continue;
4261 }
4262
4263 // Make a route to host so we check the specific interface.
4264 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4265 hostAddr.getAddress())) {
4266 // Wait a short time to be sure the route is established ??
4267 log("isMobileOk:"
4268 + " wait to establish route to hostAddr=" + hostAddr);
4269 sleep(3);
4270 } else {
4271 log("isMobileOk:"
4272 + " could not establish route to hostAddr=" + hostAddr);
4273 continue;
4274 }
4275
4276 // Rewrite the url to have numeric address to use the specific route.
Lorenzo Colitti9405bee2013-10-08 10:41:25 +09004277 URL newUrl = new URL(orgUri.getScheme(),
4278 hostAddr.getHostAddress(), orgUri.getPath());
Wink Saville32506bc2013-06-29 21:10:57 -07004279 log("isMobileOk: newUrl=" + newUrl);
4280
4281 HttpURLConnection urlConn = null;
4282 try {
4283 // Open the connection set the request header and get the response
4284 urlConn = (HttpURLConnection) newUrl.openConnection(
4285 java.net.Proxy.NO_PROXY);
4286 urlConn.setInstanceFollowRedirects(false);
4287 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4288 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4289 urlConn.setUseCaches(false);
4290 urlConn.setAllowUserInteraction(false);
Lorenzo Colitti9405bee2013-10-08 10:41:25 +09004291 // Set the "Connection" to "Close" as by default "Keep-Alive"
4292 // is used which is useless in this case.
Wink Saville32506bc2013-06-29 21:10:57 -07004293 urlConn.setRequestProperty("Connection", "close");
4294 int responseCode = urlConn.getResponseCode();
Wink Saville9685cd12013-09-06 09:53:08 -07004295
4296 // For debug display the headers
4297 Map<String, List<String>> headers = urlConn.getHeaderFields();
4298 log("isMobileOk: headers=" + headers);
4299
4300 // Close the connection
Wink Saville32506bc2013-06-29 21:10:57 -07004301 urlConn.disconnect();
4302 urlConn = null;
Wink Saville9685cd12013-09-06 09:53:08 -07004303
4304 if (responseCode == 204) {
4305 // Return
Wink Saville9685cd12013-09-06 09:53:08 -07004306 result = CMP_RESULT_CODE_CONNECTABLE;
Wink Savillee14346f2013-09-13 12:40:11 -07004307 log("isMobileOk: X expected responseCode=" + responseCode
4308 + " result=" + result);
Wink Saville9685cd12013-09-06 09:53:08 -07004309 return result;
4310 } else {
4311 // Retry to be sure this was redirected, we've gotten
4312 // occasions where a server returned 200 even though
4313 // the device didn't have a "warm" sim.
4314 log("isMobileOk: not expected responseCode=" + responseCode);
4315 result = CMP_RESULT_CODE_REDIRECTED;
4316 }
Wink Saville32506bc2013-06-29 21:10:57 -07004317 } catch (Exception e) {
4318 log("isMobileOk: HttpURLConnection Exception e=" + e);
Wink Saville9685cd12013-09-06 09:53:08 -07004319 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004320 if (urlConn != null) {
4321 urlConn.disconnect();
4322 urlConn = null;
4323 }
4324 }
4325 }
Wink Savillee14346f2013-09-13 12:40:11 -07004326 log("isMobileOk: X loops|timed out result=" + result);
Wink Saville32506bc2013-06-29 21:10:57 -07004327 return result;
4328 } catch (Exception e) {
4329 log("isMobileOk: Exception e=" + e);
4330 continue;
4331 }
4332 }
4333 log("isMobileOk: timed out");
4334 } finally {
4335 log("isMobileOk: F stop hipri");
4336 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4337 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4338 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004339
4340 // Wait for hipri to disconnect.
4341 long endTime = SystemClock.elapsedRealtime() + 5000;
4342
4343 while(SystemClock.elapsedRealtime() < endTime) {
4344 NetworkInfo.State state = mCs
4345 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4346 if (state != NetworkInfo.State.DISCONNECTED) {
4347 if (VDBG) {
4348 log("isMobileOk: connected ni=" +
4349 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4350 }
4351 sleep(1);
4352 continue;
4353 }
4354 }
4355
Wink Saville32506bc2013-06-29 21:10:57 -07004356 log("isMobileOk: X result=" + result);
4357 }
4358 return result;
4359 }
4360
4361 @Override
4362 protected Integer doInBackground(Params... params) {
4363 return isMobileOk(params[0]);
4364 }
4365
4366 @Override
4367 protected void onPostExecute(Integer result) {
4368 log("onPostExecute: result=" + result);
4369 if ((mParams != null) && (mParams.mCb != null)) {
4370 mParams.mCb.onComplete(result);
4371 }
4372 }
4373
4374 private String inetAddressesToString(InetAddress[] addresses) {
4375 StringBuffer sb = new StringBuffer();
4376 boolean firstTime = true;
4377 for(InetAddress addr : addresses) {
4378 if (firstTime) {
4379 firstTime = false;
4380 } else {
4381 sb.append(",");
4382 }
4383 sb.append(addr);
4384 }
4385 return sb.toString();
4386 }
4387
4388 private void printNetworkInfo() {
4389 boolean hasIccCard = mTm.hasIccCard();
4390 int simState = mTm.getSimState();
4391 log("hasIccCard=" + hasIccCard
4392 + " simState=" + simState);
4393 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4394 if (ni != null) {
4395 log("ni.length=" + ni.length);
4396 for (NetworkInfo netInfo: ni) {
4397 log("netInfo=" + netInfo.toString());
4398 }
4399 } else {
4400 log("no network info ni=null");
4401 }
4402 }
4403
4404 /**
4405 * Sleep for a few seconds then return.
4406 * @param seconds
4407 */
4408 private static void sleep(int seconds) {
4409 try {
4410 Thread.sleep(seconds * 1000);
4411 } catch (InterruptedException e) {
4412 e.printStackTrace();
4413 }
4414 }
4415
Wink Saville32506bc2013-06-29 21:10:57 -07004416 private void log(String s) {
4417 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4418 }
4419 }
4420
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004421 // TODO: Move to ConnectivityManager and make public?
4422 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4423 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Saville32506bc2013-06-29 21:10:57 -07004424
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004425 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4426 @Override
4427 public void onReceive(Context context, Intent intent) {
4428 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4429 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4430 }
4431 }
4432 };
4433
4434 private void handleMobileProvisioningAction(String url) {
4435 // Notication mark notification as not visible
Wink Saville76f49d32013-10-03 08:34:46 -07004436 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004437
4438 // If provisioning network handle as a special case,
4439 // otherwise launch browser with the intent directly.
4440 NetworkInfo ni = getProvisioningNetworkInfo();
Wink Savilleb1a32022013-09-05 12:02:25 -07004441 if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004442 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4443 MobileDataStateTracker mdst = (MobileDataStateTracker)
4444 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4445 mdst.enableMobileProvisioning(url);
4446 } else {
4447 if (DBG) log("handleMobileProvisioningAction: on default network");
4448 Intent newIntent =
4449 new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4450 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4451 Intent.FLAG_ACTIVITY_NEW_TASK);
4452 try {
4453 mContext.startActivity(newIntent);
4454 } catch (ActivityNotFoundException e) {
4455 loge("handleMobileProvisioningAction: startActivity failed" + e);
4456 }
4457 }
4458 }
4459
4460 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4461 private volatile boolean mIsNotificationVisible = false;
4462
4463 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4464 String url) {
4465 if (DBG) {
4466 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4467 + " extraInfo=" + extraInfo + " url=" + url);
4468 }
Wink Saville32506bc2013-06-29 21:10:57 -07004469
4470 Resources r = Resources.getSystem();
4471 NotificationManager notificationManager = (NotificationManager) mContext
4472 .getSystemService(Context.NOTIFICATION_SERVICE);
4473
4474 if (visible) {
4475 CharSequence title;
4476 CharSequence details;
4477 int icon;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004478 Intent intent;
4479 Notification notification = new Notification();
4480 switch (networkType) {
Wink Saville32506bc2013-06-29 21:10:57 -07004481 case ConnectivityManager.TYPE_WIFI:
Wink Saville32506bc2013-06-29 21:10:57 -07004482 title = r.getString(R.string.wifi_available_sign_in, 0);
4483 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004484 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004485 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004486 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4487 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4488 Intent.FLAG_ACTIVITY_NEW_TASK);
4489 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004490 break;
4491 case ConnectivityManager.TYPE_MOBILE:
4492 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Saville32506bc2013-06-29 21:10:57 -07004493 title = r.getString(R.string.network_available_sign_in, 0);
4494 // TODO: Change this to pull from NetworkInfo once a printable
4495 // name has been added to it
4496 details = mTelephonyManager.getNetworkOperatorName();
4497 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004498 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4499 intent.putExtra("EXTRA_URL", url);
4500 intent.setFlags(0);
4501 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004502 break;
4503 default:
Wink Saville32506bc2013-06-29 21:10:57 -07004504 title = r.getString(R.string.network_available_sign_in, 0);
4505 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004506 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004507 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004508 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4509 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4510 Intent.FLAG_ACTIVITY_NEW_TASK);
4511 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004512 break;
4513 }
4514
Wink Saville32506bc2013-06-29 21:10:57 -07004515 notification.when = 0;
4516 notification.icon = icon;
4517 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Saville32506bc2013-06-29 21:10:57 -07004518 notification.tickerText = title;
4519 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4520
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004521 try {
Wink Saville76f49d32013-10-03 08:34:46 -07004522 notificationManager.notify(NOTIFICATION_ID, networkType, notification);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004523 } catch (NullPointerException npe) {
4524 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4525 npe.printStackTrace();
4526 }
Wink Saville32506bc2013-06-29 21:10:57 -07004527 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004528 try {
Wink Saville76f49d32013-10-03 08:34:46 -07004529 notificationManager.cancel(NOTIFICATION_ID, networkType);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004530 } catch (NullPointerException npe) {
4531 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4532 npe.printStackTrace();
4533 }
Wink Saville32506bc2013-06-29 21:10:57 -07004534 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004535 mIsNotificationVisible = visible;
Wink Saville32506bc2013-06-29 21:10:57 -07004536 }
4537
Robert Greenwalt39d56012013-07-16 12:06:09 -07004538 /** Location to an updatable file listing carrier provisioning urls.
4539 * An example:
4540 *
4541 * <?xml version="1.0" encoding="utf-8"?>
4542 * <provisioningUrls>
4543 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4544 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4545 * </provisioningUrls>
4546 */
4547 private static final String PROVISIONING_URL_PATH =
4548 "/data/misc/radio/provisioning_urls.xml";
4549 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville32506bc2013-06-29 21:10:57 -07004550
Robert Greenwalt39d56012013-07-16 12:06:09 -07004551 /** XML tag for root element. */
4552 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4553 /** XML tag for individual url */
4554 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4555 /** XML tag for redirected url */
4556 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4557 /** XML attribute for mcc */
4558 private static final String ATTR_MCC = "mcc";
4559 /** XML attribute for mnc */
4560 private static final String ATTR_MNC = "mnc";
4561
4562 private static final int REDIRECTED_PROVISIONING = 1;
4563 private static final int PROVISIONING = 2;
4564
4565 private String getProvisioningUrlBaseFromFile(int type) {
4566 FileReader fileReader = null;
4567 XmlPullParser parser = null;
4568 Configuration config = mContext.getResources().getConfiguration();
4569 String tagType;
4570
4571 switch (type) {
4572 case PROVISIONING:
4573 tagType = TAG_PROVISIONING_URL;
4574 break;
4575 case REDIRECTED_PROVISIONING:
4576 tagType = TAG_REDIRECTED_URL;
4577 break;
4578 default:
4579 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4580 type);
4581 }
4582
4583 try {
4584 fileReader = new FileReader(mProvisioningUrlFile);
4585 parser = Xml.newPullParser();
4586 parser.setInput(fileReader);
4587 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4588
4589 while (true) {
4590 XmlUtils.nextElement(parser);
4591
4592 String element = parser.getName();
4593 if (element == null) break;
4594
4595 if (element.equals(tagType)) {
4596 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4597 try {
4598 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4599 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4600 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4601 parser.next();
4602 if (parser.getEventType() == XmlPullParser.TEXT) {
4603 return parser.getText();
4604 }
4605 }
4606 }
4607 } catch (NumberFormatException e) {
4608 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4609 }
4610 }
4611 }
4612 return null;
4613 } catch (FileNotFoundException e) {
4614 loge("Carrier Provisioning Urls file not found");
4615 } catch (XmlPullParserException e) {
4616 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4617 } catch (IOException e) {
4618 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4619 } finally {
4620 if (fileReader != null) {
4621 try {
4622 fileReader.close();
4623 } catch (IOException e) {}
4624 }
4625 }
4626 return null;
4627 }
4628
Wink Saville8432cf42013-07-20 20:31:59 -07004629 @Override
4630 public String getMobileRedirectedProvisioningUrl() {
4631 enforceConnectivityInternalPermission();
Robert Greenwalt39d56012013-07-16 12:06:09 -07004632 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4633 if (TextUtils.isEmpty(url)) {
4634 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4635 }
4636 return url;
4637 }
4638
Wink Saville8432cf42013-07-20 20:31:59 -07004639 @Override
Robert Greenwalt39d56012013-07-16 12:06:09 -07004640 public String getMobileProvisioningUrl() {
4641 enforceConnectivityInternalPermission();
4642 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4643 if (TextUtils.isEmpty(url)) {
4644 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville8432cf42013-07-20 20:31:59 -07004645 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004646 } else {
Wink Saville8432cf42013-07-20 20:31:59 -07004647 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004648 }
Wink Savillec118d7e2013-07-10 23:00:07 -07004649 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville32506bc2013-06-29 21:10:57 -07004650 if (!TextUtils.isEmpty(url)) {
Wink Savillec118d7e2013-07-10 23:00:07 -07004651 String phoneNumber = mTelephonyManager.getLine1Number();
4652 if (TextUtils.isEmpty(phoneNumber)) {
4653 phoneNumber = "0000000000";
4654 }
Wink Saville32506bc2013-06-29 21:10:57 -07004655 url = String.format(url,
4656 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4657 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savillec118d7e2013-07-10 23:00:07 -07004658 phoneNumber /* Phone numer */);
Wink Saville32506bc2013-06-29 21:10:57 -07004659 }
4660
Wink Saville32506bc2013-06-29 21:10:57 -07004661 return url;
4662 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07004663
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004664 @Override
4665 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4666 String extraInfo, String url) {
4667 enforceConnectivityInternalPermission();
4668 setProvNotificationVisible(visible, networkType, extraInfo, url);
4669 }
Wink Savillecb117d32013-08-29 14:57:08 -07004670
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07004671 @Override
4672 public void setAirplaneMode(boolean enable) {
4673 enforceConnectivityInternalPermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07004674 final long ident = Binder.clearCallingIdentity();
4675 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07004676 final ContentResolver cr = mContext.getContentResolver();
4677 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
4678 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4679 intent.putExtra("state", enable);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07004680 mContext.sendBroadcast(intent);
4681 } finally {
4682 Binder.restoreCallingIdentity(ident);
4683 }
4684 }
4685
Chad Brubakerb7652cd2013-06-14 11:16:51 -07004686 private void onUserStart(int userId) {
4687 synchronized(mVpns) {
4688 Vpn userVpn = mVpns.get(userId);
4689 if (userVpn != null) {
4690 loge("Starting user already has a VPN");
4691 return;
4692 }
4693 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4694 mVpns.put(userId, userVpn);
4695 userVpn.startMonitoring(mContext, mTrackerHandler);
4696 }
4697 }
4698
4699 private void onUserStop(int userId) {
4700 synchronized(mVpns) {
4701 Vpn userVpn = mVpns.get(userId);
4702 if (userVpn == null) {
4703 loge("Stopping user has no VPN");
4704 return;
4705 }
4706 mVpns.delete(userId);
4707 }
4708 }
4709
4710 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4711 @Override
4712 public void onReceive(Context context, Intent intent) {
4713 final String action = intent.getAction();
4714 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4715 if (userId == UserHandle.USER_NULL) return;
4716
4717 if (Intent.ACTION_USER_STARTING.equals(action)) {
4718 onUserStart(userId);
4719 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4720 onUserStop(userId);
4721 }
4722 }
4723 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004724
4725 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004726 public LinkQualityInfo getLinkQualityInfo(int networkType) {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004727 enforceAccessPermission();
4728 if (isNetworkTypeValid(networkType)) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004729 return mNetTrackers[networkType].getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004730 } else {
4731 return null;
4732 }
4733 }
4734
4735 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004736 public LinkQualityInfo getActiveLinkQualityInfo() {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004737 enforceAccessPermission();
4738 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004739 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004740 } else {
4741 return null;
4742 }
4743 }
4744
4745 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004746 public LinkQualityInfo[] getAllLinkQualityInfo() {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004747 enforceAccessPermission();
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004748 final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004749 for (NetworkStateTracker tracker : mNetTrackers) {
4750 if (tracker != null) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004751 LinkQualityInfo li = tracker.getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004752 if (li != null) {
4753 result.add(li);
4754 }
4755 }
4756 }
4757
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004758 return result.toArray(new LinkQualityInfo[result.size()]);
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004759 }
4760
4761 /* Infrastructure for network sampling */
4762
4763 private void handleNetworkSamplingTimeout() {
4764
4765 log("Sampling interval elapsed, updating statistics ..");
4766
4767 // initialize list of interfaces ..
4768 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4769 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4770 for (NetworkStateTracker tracker : mNetTrackers) {
4771 if (tracker != null) {
4772 String ifaceName = tracker.getNetworkInterfaceName();
4773 if (ifaceName != null) {
4774 mapIfaceToSample.put(ifaceName, null);
4775 }
4776 }
4777 }
4778
4779 // Read samples for all interfaces
4780 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4781
4782 // process samples for all networks
4783 for (NetworkStateTracker tracker : mNetTrackers) {
4784 if (tracker != null) {
4785 String ifaceName = tracker.getNetworkInterfaceName();
4786 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4787 if (ss != null) {
4788 // end the previous sampling cycle
4789 tracker.stopSampling(ss);
4790 // start a new sampling cycle ..
4791 tracker.startSampling(ss);
4792 }
4793 }
4794 }
4795
4796 log("Done.");
4797
4798 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4799 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4800 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4801
4802 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4803
4804 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
4805 }
4806
4807 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
4808 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
4809 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
4810 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004811}