blob: 47f18e7335616668d6b84d22e43c2955a5b57223 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baib5da5752012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070023import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
24import static android.net.ConnectivityManager.TYPE_DUMMY;
25import static android.net.ConnectivityManager.TYPE_ETHERNET;
26import static android.net.ConnectivityManager.TYPE_MOBILE;
27import static android.net.ConnectivityManager.TYPE_WIFI;
28import static android.net.ConnectivityManager.TYPE_WIMAX;
29import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070030import static android.net.ConnectivityManager.isNetworkTypeValid;
31import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070033
Vinit Deshapnde30ad2542013-08-21 13:09:01 -070034import android.app.AlarmManager;
Wink Saville32506bc2013-06-29 21:10:57 -070035import android.app.Notification;
36import android.app.NotificationManager;
37import android.app.PendingIntent;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080038import android.bluetooth.BluetoothTetheringDataTracker;
Wink Saville9a1a7ef2013-08-29 08:55:16 -070039import android.content.ActivityNotFoundException;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090043import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080044import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070045import android.content.IntentFilter;
The Android Open Source Project28527d22009-03-03 19:31:44 -080046import android.content.pm.PackageManager;
Robert Greenwalt39d56012013-07-16 12:06:09 -070047import android.content.res.Configuration;
tk.mun093f55c2011-10-13 22:51:57 +090048import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070049import android.database.ContentObserver;
Irfan Sheriff0ad0d132012-08-16 12:49:23 -070050import android.net.CaptivePortalTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080051import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080052import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080053import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070055import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070056import android.net.INetworkPolicyListener;
57import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070058import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070059import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080060import android.net.LinkProperties;
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -070061import android.net.LinkQualityInfo;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070062import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070064import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070066import android.net.NetworkInfo.DetailedState;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070067import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070068import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080069import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070070import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070071import android.net.Proxy;
72import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070073import android.net.RouteInfo;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -070074import android.net.SamplingDataTracker;
Jason Monka5bf2842013-07-03 17:04:33 -040075import android.net.Uri;
The Android Open Source Project28527d22009-03-03 19:31:44 -080076import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090077import android.net.wimax.WimaxManagerConstants;
Wink Saville32506bc2013-06-29 21:10:57 -070078import android.os.AsyncTask;
The Android Open Source Project28527d22009-03-03 19:31:44 -080079import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040080import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080081import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070082import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070083import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070084import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080085import android.os.Looper;
86import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070087import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070088import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070089import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -070090import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070091import android.os.RemoteException;
Wink Saville32506bc2013-06-29 21:10:57 -070092import android.os.ResultReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080093import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070094import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080095import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -070096import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080097import android.provider.Settings;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070098import android.security.Credentials;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -070099import android.security.KeyStore;
Wink Saville32506bc2013-06-29 21:10:57 -0700100import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700101import android.text.TextUtils;
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800102import android.util.Slog;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700103import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700104import android.util.SparseIntArray;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700105import android.util.Xml;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800106
Wink Saville32506bc2013-06-29 21:10:57 -0700107import com.android.internal.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400108import com.android.internal.annotations.GuardedBy;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700109import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700110import com.android.internal.net.VpnConfig;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700111import com.android.internal.net.VpnProfile;
Wink Saville32506bc2013-06-29 21:10:57 -0700112import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700113import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700114import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700115import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700116import com.android.internal.util.XmlUtils;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700117import com.android.server.am.BatteryStatsService;
John Spurlock1f5cec72013-06-24 14:20:23 -0400118import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900119import com.android.server.connectivity.Nat464Xlat;
Jason Monka5bf2842013-07-03 17:04:33 -0400120import com.android.server.connectivity.PacManager;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800121import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700122import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700123import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700124import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700125import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700126import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700127
tk.mun093f55c2011-10-13 22:51:57 +0900128import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700129
Robert Greenwalt39d56012013-07-16 12:06:09 -0700130import org.xmlpull.v1.XmlPullParser;
131import org.xmlpull.v1.XmlPullParserException;
132
133import java.io.File;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800134import java.io.FileDescriptor;
Robert Greenwalt39d56012013-07-16 12:06:09 -0700135import java.io.FileNotFoundException;
136import java.io.FileReader;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700137import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800138import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900139import java.lang.reflect.Constructor;
Wink Saville32506bc2013-06-29 21:10:57 -0700140import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700141import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700142import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700143import java.net.InetAddress;
Wink Saville32506bc2013-06-29 21:10:57 -0700144import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700145import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700146import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700147import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700148import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700149import java.util.GregorianCalendar;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700150import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700151import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700152import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700153import java.util.Map;
Wink Saville32506bc2013-06-29 21:10:57 -0700154import java.util.Random;
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700155import java.util.concurrent.atomic.AtomicBoolean;
Wink Saville32506bc2013-06-29 21:10:57 -0700156import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800157
158/**
159 * @hide
160 */
161public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700162 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800163
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700164 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700165 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800166
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700167 private static final boolean LOGD_RULES = false;
168
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700169 // TODO: create better separation between radio types and network types
170
Robert Greenwalt2034b912009-08-12 16:08:25 -0700171 // how long to wait before switching back to a radio's default network
172 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
173 // system property that can override the above value
174 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
175 "android.telephony.apn-restore";
176
Wink Saville32506bc2013-06-29 21:10:57 -0700177 // Default value if FAIL_FAST_TIME_MS is not set
178 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
179 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
180 private static final String FAIL_FAST_TIME_MS =
181 "persist.radio.fail_fast_time_ms";
182
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700183 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
184 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
185
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -0700186 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700187
188 private PendingIntent mSampleIntervalElapsedIntent;
189
190 // Set network sampling interval at 12 minutes, this way, even if the timers get
191 // aggregated, it will fire at around 15 minutes, which should allow us to
192 // aggregate this timer with other timers (specially the socket keep alive timers)
193 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
194
195 // start network sampling a minute after booting ...
196 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
197
198 AlarmManager mAlarmManager;
199
Robert Greenwaltbd492212011-05-06 17:10:53 -0700200 // used in recursive route setting to add gateways for the host for which
201 // a host route was requested.
202 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
203
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800204 private Tethering mTethering;
205
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700206 private KeyStore mKeyStore;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700207
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700208 @GuardedBy("mVpns")
209 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700210 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700211
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700212 private boolean mLockdownEnabled;
213 private LockdownVpnTracker mLockdownTracker;
214
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900215 private Nat464Xlat mClat;
216
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700217 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
218 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700219 /** Currently active network rules by UID. */
220 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700221 /** Set of ifaces that are costly. */
222 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700223
The Android Open Source Project28527d22009-03-03 19:31:44 -0800224 /**
225 * Sometimes we want to refer to the individual network state
226 * trackers separately, and sometimes we just want to treat them
227 * abstractly.
228 */
229 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700230
Irfan Sheriff0ad0d132012-08-16 12:49:23 -0700231 /* Handles captive portal check on a network */
232 private CaptivePortalTracker mCaptivePortalTracker;
233
Robert Greenwalt2034b912009-08-12 16:08:25 -0700234 /**
Wink Saville051a6642011-07-13 13:44:13 -0700235 * The link properties that define the current links
236 */
237 private LinkProperties mCurrentLinkProperties[];
238
239 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700240 * A per Net list of the PID's that requested access to the net
241 * used both as a refcount and for per-PID DNS selection
242 */
Mattias Falkd697aa22011-08-23 14:15:13 +0200243 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700244
Robert Greenwalt2034b912009-08-12 16:08:25 -0700245 // priority order of the nettrackers
246 // (excluding dynamically set mNetworkPreference)
247 // TODO - move mNetworkTypePreference into this
248 private int[] mPriorityList;
249
The Android Open Source Project28527d22009-03-03 19:31:44 -0800250 private Context mContext;
251 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700252 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700253 // 0 is full bad, 100 is full good
Wink Saville151eaa62013-01-31 00:30:13 +0000254 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700255 private int mDefaultInetConditionPublished = 0;
256 private boolean mInetConditionChangeInFlight = false;
257 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800258
Chia-chi Yehcc844502011-07-14 18:01:57 -0700259 private Object mDnsLock = new Object();
Robert Greenwalte41e3b32013-02-11 15:25:10 -0800260 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800261
262 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700263 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800264
Robert Greenwalt355205c2011-05-10 15:05:02 -0700265 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700266 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700267
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700268 private static final int ENABLED = 1;
269 private static final int DISABLED = 0;
270
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700271 private static final boolean ADD = true;
272 private static final boolean REMOVE = false;
273
274 private static final boolean TO_DEFAULT_TABLE = true;
275 private static final boolean TO_SECONDARY_TABLE = false;
276
Chad Brubaker49db4222013-07-15 16:34:04 -0700277 private static final boolean EXEMPT = true;
278 private static final boolean UNEXEMPT = false;
279
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700280 /**
281 * used internally as a delayed event to make us switch back to the
282 * default network
283 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700284 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700285
286 /**
287 * used internally to change our mobile data enabled flag
288 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700289 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700290
291 /**
292 * used internally to change our network preference setting
293 * arg1 = networkType to prefer
294 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700295 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700296
297 /**
298 * used internally to synchronize inet condition reports
299 * arg1 = networkType
300 * arg2 = condition (0 bad, 100 good)
301 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700302 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700303
304 /**
305 * used internally to mark the end of inet condition hold periods
306 * arg1 = networkType
307 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700308 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700309
310 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700311 * used internally to set enable/disable cellular data
312 * arg1 = ENBALED or DISABLED
313 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700314 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700315
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700316 /**
317 * used internally to clear a wakelock when transitioning
318 * from one net to another
319 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700320 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700321
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700322 /**
323 * used internally to reload global proxy settings
324 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700325 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700326
Robert Greenwalt34848c02011-03-25 13:09:25 -0700327 /**
328 * used internally to set external dependency met/unmet
329 * arg1 = ENABLED (met) or DISABLED (unmet)
330 * arg2 = NetworkType
331 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700332 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700333
Chia-chi Yehcc844502011-07-14 18:01:57 -0700334 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700335 * used internally to send a sticky broadcast delayed.
336 */
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700337 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700338
Jeff Sharkey805662d2011-08-19 02:24:24 -0700339 /**
340 * Used internally to
341 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
342 */
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700343 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700344
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700345 private static final int EVENT_VPN_STATE_CHANGED = 13;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700346
Wink Saville32506bc2013-06-29 21:10:57 -0700347 /**
348 * Used internally to disable fail fast of mobile data
349 */
Chad Brubaker5fdc1462013-07-23 17:44:41 -0700350 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Saville32506bc2013-06-29 21:10:57 -0700351
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700352 /**
353 * user internally to indicate that data sampling interval is up
354 */
355 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
356
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700357 /** Handler used for internal events. */
358 private InternalHandler mHandler;
359 /** Handler used for incoming {@link NetworkStateTracker} events. */
360 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700361
362 // list of DeathRecipients used to make sure features are turned off when
363 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500364 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700365
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400366 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800367 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400368
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700369 private PowerManager.WakeLock mNetTransitionWakeLock;
370 private String mNetTransitionWakeLockCausedBy = "";
371 private int mNetTransitionWakeLockSerialNumber;
372 private int mNetTransitionWakeLockTimeout;
373
Robert Greenwalt94daa182010-09-01 11:34:05 -0700374 private InetAddress mDefaultDns;
375
Chad Brubaker49db4222013-07-15 16:34:04 -0700376 // Lock for protecting access to mAddedRoutes and mExemptAddresses
377 private final Object mRoutesLock = new Object();
378
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700379 // this collection is used to refcount the added routes - if there are none left
380 // it's time to remove the route from the route table
Chad Brubaker49db4222013-07-15 16:34:04 -0700381 @GuardedBy("mRoutesLock")
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700382 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
383
Chad Brubaker49db4222013-07-15 16:34:04 -0700384 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
385 // used to handle cleanup of exempt rules
386 @GuardedBy("mRoutesLock")
387 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
388
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700389 // used in DBG mode to track inet condition reports
390 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
391 private ArrayList mInetLog;
392
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700393 // track the current default http proxy - tell the world if we get a new one (real change)
394 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltf9661d32013-04-05 17:14:19 -0700395 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700396 private boolean mDefaultProxyDisabled = false;
397
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700398 // track the global proxy.
399 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700400
Jason Monka5bf2842013-07-03 17:04:33 -0400401 private PacManager mPacManager = null;
402
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700403 private SettingsObserver mSettingsObserver;
404
Robert Greenwalt34848c02011-03-25 13:09:25 -0700405 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700406 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700407
Robert Greenwalt12c44552009-12-07 11:33:18 -0800408 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700409 public int mSimultaneity;
410 public int mType;
411 public RadioAttributes(String init) {
412 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700413 mType = Integer.parseInt(fragments[0]);
414 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700415 }
416 }
417 RadioAttributes[] mRadioAttributes;
418
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700419 // the set of network types that can only be enabled by system/sig apps
420 List mProtectedNetworks;
421
John Spurlock1f5cec72013-06-24 14:20:23 -0400422 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700423
Wink Saville32506bc2013-06-29 21:10:57 -0700424 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
425
426 TelephonyManager mTelephonyManager;
John Spurlock1f5cec72013-06-24 14:20:23 -0400427
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700428 public ConnectivityService(Context context, INetworkManagementService netd,
429 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700430 // Currently, omitting a NetworkFactory will create one internally
431 // TODO: create here when we have cleaner WiMAX support
432 this(context, netd, statsService, policyManager, null);
433 }
434
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700435 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700436 INetworkStatsService statsService, INetworkPolicyManager policyManager,
437 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800438 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800439
Wink Saville775aad62010-09-02 19:23:52 -0700440 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
441 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700442 mHandler = new InternalHandler(handlerThread.getLooper());
443 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700444
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700445 if (netFactory == null) {
446 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
447 }
448
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800449 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800450 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
451 String id = Settings.Secure.getString(context.getContentResolver(),
452 Settings.Secure.ANDROID_ID);
453 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700454 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800455 SystemProperties.set("net.hostname", name);
456 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800457 }
458
Robert Greenwalt94daa182010-09-01 11:34:05 -0700459 // read our default dns server ip
Jeff Sharkey8c870452012-09-26 22:03:49 -0700460 String dns = Settings.Global.getString(context.getContentResolver(),
461 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700462 if (dns == null || dns.length() == 0) {
463 dns = context.getResources().getString(
464 com.android.internal.R.string.config_default_dns_server);
465 }
466 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800467 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
468 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800469 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700470 }
471
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700472 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700473 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700474 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700475 mKeyStore = KeyStore.getInstance();
Wink Saville32506bc2013-06-29 21:10:57 -0700476 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700477
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700478 try {
479 mPolicyManager.registerListener(mPolicyListener);
480 } catch (RemoteException e) {
481 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700482 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700483 }
484
485 final PowerManager powerManager = (PowerManager) context.getSystemService(
486 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700487 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
488 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
489 com.android.internal.R.integer.config_networkTransitionTimeout);
490
Robert Greenwalt2034b912009-08-12 16:08:25 -0700491 mNetTrackers = new NetworkStateTracker[
492 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700493 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700494
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700495 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700496 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700497
Robert Greenwalt2034b912009-08-12 16:08:25 -0700498 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700499 String[] raStrings = context.getResources().getStringArray(
500 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700501 for (String raString : raStrings) {
502 RadioAttributes r = new RadioAttributes(raString);
Wink Saville512c2202013-07-29 15:00:57 -0700503 if (VDBG) log("raString=" + raString + " r=" + r);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700504 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800505 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700506 continue;
507 }
508 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800509 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700510 r.mType);
511 continue;
512 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700513 mRadioAttributes[r.mType] = r;
514 }
515
Wink Saville00fe5092013-04-23 14:26:51 -0700516 // TODO: What is the "correct" way to do determine if this is a wifi only device?
517 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
518 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700519 String[] naStrings = context.getResources().getStringArray(
520 com.android.internal.R.array.networkAttributes);
521 for (String naString : naStrings) {
522 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700523 NetworkConfig n = new NetworkConfig(naString);
Wink Saville512c2202013-07-29 15:00:57 -0700524 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Savillef2a62832011-04-07 14:23:45 -0700525 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800526 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700527 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700528 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700529 }
Wink Saville00fe5092013-04-23 14:26:51 -0700530 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
531 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
532 n.type);
533 continue;
534 }
Wink Savillef2a62832011-04-07 14:23:45 -0700535 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800536 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700537 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700538 continue;
539 }
Wink Savillef2a62832011-04-07 14:23:45 -0700540 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800541 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700542 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700543 continue;
544 }
Wink Savillef2a62832011-04-07 14:23:45 -0700545 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700546 mNetworksDefined++;
547 } catch(Exception e) {
548 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700549 }
550 }
Wink Saville512c2202013-07-29 15:00:57 -0700551 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700552
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700553 mProtectedNetworks = new ArrayList<Integer>();
554 int[] protectedNetworks = context.getResources().getIntArray(
555 com.android.internal.R.array.config_protectedNetworks);
556 for (int p : protectedNetworks) {
557 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
558 mProtectedNetworks.add(p);
559 } else {
560 if (DBG) loge("Ignoring protectedNetwork " + p);
561 }
562 }
563
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700564 // high priority first
565 mPriorityList = new int[mNetworksDefined];
566 {
567 int insertionPoint = mNetworksDefined-1;
568 int currentLowest = 0;
569 int nextLowest = 0;
570 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700571 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700572 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700573 if (na.priority < currentLowest) continue;
574 if (na.priority > currentLowest) {
575 if (na.priority < nextLowest || nextLowest == 0) {
576 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700577 }
578 continue;
579 }
Wink Savillef2a62832011-04-07 14:23:45 -0700580 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700581 }
582 currentLowest = nextLowest;
583 nextLowest = 0;
584 }
585 }
586
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800587 // Update mNetworkPreference according to user mannually first then overlay config.xml
588 mNetworkPreference = getPersistedNetworkPreference();
589 if (mNetworkPreference == -1) {
590 for (int n : mPriorityList) {
591 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
592 mNetworkPreference = n;
593 break;
594 }
595 }
596 if (mNetworkPreference == -1) {
597 throw new IllegalStateException(
598 "You should set at least one default Network in config.xml!");
599 }
600 }
601
Mattias Falkd697aa22011-08-23 14:15:13 +0200602 mNetRequestersPids =
603 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700604 for (int i : mPriorityList) {
Mattias Falkd697aa22011-08-23 14:15:13 +0200605 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700606 }
607
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500608 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700609
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700610 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
611 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700612
613 // Create and start trackers for hard-coded networks
614 for (int targetNetworkType : mPriorityList) {
615 final NetworkConfig config = mNetConfigs[targetNetworkType];
616 final NetworkStateTracker tracker;
617 try {
618 tracker = netFactory.createTracker(targetNetworkType, config);
619 mNetTrackers[targetNetworkType] = tracker;
620 } catch (IllegalArgumentException e) {
621 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
622 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700623 continue;
624 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700625
626 tracker.startMonitoring(context, mTrackerHandler);
627 if (config.isDefault()) {
628 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800629 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700630 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800631
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700632 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800633
Robert Greenwaltf68291a2013-07-19 14:30:49 -0700634 //set up the listener for user state for creating user VPNs
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700635 IntentFilter intentFilter = new IntentFilter();
636 intentFilter.addAction(Intent.ACTION_USER_STARTING);
637 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
638 mContext.registerReceiverAsUser(
639 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900640 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
641
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700642 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700643 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700644 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900645 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700646 } catch (RemoteException e) {
647 loge("Error registering observer :" + e);
648 }
649
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700650 if (DBG) {
651 mInetLog = new ArrayList();
652 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700653
654 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
655 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800656
John Spurlock1f5cec72013-06-24 14:20:23 -0400657 mDataConnectionStats = new DataConnectionStats(mContext);
658 mDataConnectionStats.startMonitoring();
Jason Monka5bf2842013-07-03 17:04:33 -0400659
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700660 // start network sampling ..
661 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
662 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -0700663 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700664
665 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
666 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
667
668 IntentFilter filter = new IntentFilter();
669 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
670 mContext.registerReceiver(
671 new BroadcastReceiver() {
672 @Override
673 public void onReceive(Context context, Intent intent) {
674 String action = intent.getAction();
675 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
676 mHandler.sendMessage(mHandler.obtainMessage
677 (EVENT_SAMPLE_INTERVAL_ELAPSED));
678 }
679 }
680 },
681 new IntentFilter(filter));
682
Jason Monka5bf2842013-07-03 17:04:33 -0400683 mPacManager = new PacManager(mContext);
Wink Savillecb117d32013-08-29 14:57:08 -0700684
685 filter = new IntentFilter();
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700686 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
687 mContext.registerReceiver(mProvisioningReceiver, filter);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800688 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700689
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700690 /**
691 * Factory that creates {@link NetworkStateTracker} instances using given
692 * {@link NetworkConfig}.
693 */
694 public interface NetworkFactory {
695 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
696 }
697
698 private static class DefaultNetworkFactory implements NetworkFactory {
699 private final Context mContext;
700 private final Handler mTrackerHandler;
701
702 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
703 mContext = context;
704 mTrackerHandler = trackerHandler;
705 }
706
707 @Override
708 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
709 switch (config.radio) {
710 case TYPE_WIFI:
711 return new WifiStateTracker(targetNetworkType, config.name);
712 case TYPE_MOBILE:
713 return new MobileDataStateTracker(targetNetworkType, config.name);
714 case TYPE_DUMMY:
715 return new DummyDataStateTracker(targetNetworkType, config.name);
716 case TYPE_BLUETOOTH:
717 return BluetoothTetheringDataTracker.getInstance();
718 case TYPE_WIMAX:
719 return makeWimaxStateTracker(mContext, mTrackerHandler);
720 case TYPE_ETHERNET:
721 return EthernetDataTracker.getInstance();
722 default:
723 throw new IllegalArgumentException(
724 "Trying to create a NetworkStateTracker for an unknown radio type: "
725 + config.radio);
726 }
727 }
728 }
729
730 /**
731 * Loads external WiMAX library and registers as system service, returning a
732 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
733 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
734 */
735 private static NetworkStateTracker makeWimaxStateTracker(
736 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700737 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900738 DexClassLoader wimaxClassLoader;
739 Class wimaxStateTrackerClass = null;
740 Class wimaxServiceClass = null;
741 Class wimaxManagerClass;
742 String wimaxJarLocation;
743 String wimaxLibLocation;
744 String wimaxManagerClassName;
745 String wimaxServiceClassName;
746 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800747
tk.mun093f55c2011-10-13 22:51:57 +0900748 NetworkStateTracker wimaxStateTracker = null;
749
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700750 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900751 com.android.internal.R.bool.config_wimaxEnabled);
752
753 if (isWimaxEnabled) {
754 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700755 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900756 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700757 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900758 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700759 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900760 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700761 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900762 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700763 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900764 com.android.internal.R.string.config_wimaxStateTrackerClassname);
765
Dianne Hackborndc456a62012-11-08 11:12:09 -0800766 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900767 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700768 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900769 wimaxLibLocation, ClassLoader.getSystemClassLoader());
770
771 try {
772 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
773 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
774 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
775 } catch (ClassNotFoundException ex) {
776 loge("Exception finding Wimax classes: " + ex.toString());
777 return null;
778 }
779 } catch(Resources.NotFoundException ex) {
780 loge("Wimax Resources does not exist!!! ");
781 return null;
782 }
783
784 try {
Dianne Hackborndc456a62012-11-08 11:12:09 -0800785 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900786
787 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
788 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700789 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
790 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900791
792 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
793 (new Class[] {Context.class, wimaxStateTrackerClass});
794 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700795 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900796 wmxSrvConst.setAccessible(false);
797
798 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
799
800 } catch(Exception ex) {
801 loge("Exception creating Wimax classes: " + ex.toString());
802 return null;
803 }
804 } else {
805 loge("Wimax is not enabled or not added to the network attributes!!! ");
806 return null;
807 }
808
809 return wimaxStateTracker;
810 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700811
The Android Open Source Project28527d22009-03-03 19:31:44 -0800812 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700813 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800814 * @param preference the new preference
815 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700816 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800817 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700818
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700819 mHandler.sendMessage(
820 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800821 }
822
823 public int getNetworkPreference() {
824 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700825 int preference;
826 synchronized(this) {
827 preference = mNetworkPreference;
828 }
829 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800830 }
831
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700832 private void handleSetNetworkPreference(int preference) {
833 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700834 mNetConfigs[preference] != null &&
835 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700836 if (mNetworkPreference != preference) {
837 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownc67cf562012-09-25 15:03:20 -0700838 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700839 synchronized(this) {
840 mNetworkPreference = preference;
841 }
842 enforcePreference();
843 }
844 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800845 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700846
Wink Saville4f0de1e2011-08-04 15:01:58 -0700847 private int getConnectivityChangeDelay() {
848 final ContentResolver cr = mContext.getContentResolver();
849
850 /** Check system properties for the default value then use secure settings value, if any. */
851 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey8c870452012-09-26 22:03:49 -0700852 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
853 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
854 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700855 defaultDelay);
856 }
857
The Android Open Source Project28527d22009-03-03 19:31:44 -0800858 private int getPersistedNetworkPreference() {
859 final ContentResolver cr = mContext.getContentResolver();
860
Jeff Brownc67cf562012-09-25 15:03:20 -0700861 final int networkPrefSetting = Settings.Global
862 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800863
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800864 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800865 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700866
The Android Open Source Project28527d22009-03-03 19:31:44 -0800867 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700868 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800869 * In this method, we only tear down a non-preferred network. Establishing
870 * a connection to the preferred network is taken care of when we handle
871 * the disconnect event from the non-preferred network
872 * (see {@link #handleDisconnect(NetworkInfo)}).
873 */
874 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700875 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800876 return;
877
Robert Greenwalt2034b912009-08-12 16:08:25 -0700878 if (!mNetTrackers[mNetworkPreference].isAvailable())
879 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800880
Robert Greenwalt2034b912009-08-12 16:08:25 -0700881 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700882 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700883 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700884 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800885 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700886 " in enforcePreference");
887 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700888 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800889 }
890 }
891 }
892
893 private boolean teardown(NetworkStateTracker netTracker) {
894 if (netTracker.teardown()) {
895 netTracker.setTeardownRequested(true);
896 return true;
897 } else {
898 return false;
899 }
900 }
901
902 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700903 * Check if UID should be blocked from using the network represented by the
904 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700905 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700906 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
907 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700908
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700909 final boolean networkCostly;
910 final int uidRules;
911 synchronized (mRulesLock) {
912 networkCostly = mMeteredIfaces.contains(iface);
913 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700914 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700915
916 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
917 return true;
918 }
919
920 // no restrictive rules; network is visible
921 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700922 }
923
924 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700925 * Return a filtered {@link NetworkInfo}, potentially marked
926 * {@link DetailedState#BLOCKED} based on
927 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700928 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700929 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
930 NetworkInfo info = tracker.getNetworkInfo();
931 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700932 // network is blocked; clone and override state
933 info = new NetworkInfo(info);
934 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700935 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700936 if (mLockdownTracker != null) {
937 info = mLockdownTracker.augmentNetworkInfo(info);
938 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700939 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700940 }
941
942 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800943 * Return NetworkInfo for the active (i.e., connected) network interface.
944 * It is assumed that at most one network is active at a time. If more
945 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700946 * @return the info for the active network, or {@code null} if none is
947 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800948 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700949 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800950 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700951 enforceAccessPermission();
952 final int uid = Binder.getCallingUid();
953 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800954 }
955
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700956 /**
957 * Find the first Provisioning network.
958 *
959 * @return NetworkInfo or null if none.
960 */
961 private NetworkInfo getProvisioningNetworkInfo() {
962 enforceAccessPermission();
963
964 // Find the first Provisioning Network
965 NetworkInfo provNi = null;
966 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Savilleb1a32022013-09-05 12:02:25 -0700967 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -0700968 provNi = ni;
969 break;
970 }
971 }
972 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
973 return provNi;
974 }
975
976 /**
977 * Find the first Provisioning network or the ActiveDefaultNetwork
978 * if there is no Provisioning network
979 *
980 * @return NetworkInfo or null if none.
981 */
982 @Override
983 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
984 enforceAccessPermission();
985
986 NetworkInfo provNi = getProvisioningNetworkInfo();
987 if (provNi == null) {
988 final int uid = Binder.getCallingUid();
989 provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
990 }
991 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
992 return provNi;
993 }
994
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700995 public NetworkInfo getActiveNetworkInfoUnfiltered() {
996 enforceAccessPermission();
997 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
998 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
999 if (tracker != null) {
1000 return tracker.getNetworkInfo();
1001 }
1002 }
1003 return null;
1004 }
1005
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001006 @Override
1007 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1008 enforceConnectivityInternalPermission();
1009 return getNetworkInfo(mActiveDefaultNetwork, uid);
1010 }
1011
1012 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001013 public NetworkInfo getNetworkInfo(int networkType) {
1014 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001015 final int uid = Binder.getCallingUid();
1016 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001017 }
1018
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001019 private NetworkInfo getNetworkInfo(int networkType, int uid) {
1020 NetworkInfo info = null;
1021 if (isNetworkTypeValid(networkType)) {
1022 final NetworkStateTracker tracker = mNetTrackers[networkType];
1023 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001024 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001025 }
1026 }
1027 return info;
1028 }
1029
1030 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001031 public NetworkInfo[] getAllNetworkInfo() {
1032 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001033 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -07001034 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001035 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001036 for (NetworkStateTracker tracker : mNetTrackers) {
1037 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001038 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001039 }
1040 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001041 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001042 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001043 }
1044
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001045 @Override
1046 public boolean isNetworkSupported(int networkType) {
1047 enforceAccessPermission();
1048 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
1049 }
1050
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001051 /**
1052 * Return LinkProperties for the active (i.e., connected) default
1053 * network interface. It is assumed that at most one default network
1054 * is active at a time. If more than one is active, it is indeterminate
1055 * which will be returned.
1056 * @return the ip properties for the active network, or {@code null} if
1057 * none is active
1058 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001059 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001060 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -07001061 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001062 }
1063
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001064 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001065 public LinkProperties getLinkProperties(int networkType) {
1066 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001067 if (isNetworkTypeValid(networkType)) {
1068 final NetworkStateTracker tracker = mNetTrackers[networkType];
1069 if (tracker != null) {
1070 return tracker.getLinkProperties();
1071 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001072 }
1073 return null;
1074 }
1075
Jeff Sharkey21062e72011-05-28 20:56:34 -07001076 @Override
1077 public NetworkState[] getAllNetworkState() {
1078 enforceAccessPermission();
1079 final int uid = Binder.getCallingUid();
1080 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001081 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -07001082 for (NetworkStateTracker tracker : mNetTrackers) {
1083 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001084 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -07001085 result.add(new NetworkState(
1086 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1087 }
1088 }
1089 }
1090 return result.toArray(new NetworkState[result.size()]);
1091 }
1092
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001093 private NetworkState getNetworkStateUnchecked(int networkType) {
1094 if (isNetworkTypeValid(networkType)) {
1095 final NetworkStateTracker tracker = mNetTrackers[networkType];
1096 if (tracker != null) {
1097 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1098 tracker.getLinkCapabilities());
1099 }
1100 }
1101 return null;
1102 }
1103
1104 @Override
1105 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1106 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001107
1108 final long token = Binder.clearCallingIdentity();
1109 try {
1110 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1111 if (state != null) {
1112 try {
1113 return mPolicyManager.getNetworkQuotaInfo(state);
1114 } catch (RemoteException e) {
1115 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001116 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001117 return null;
1118 } finally {
1119 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001120 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001121 }
1122
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001123 @Override
1124 public boolean isActiveNetworkMetered() {
1125 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001126 final long token = Binder.clearCallingIdentity();
1127 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001128 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001129 } finally {
1130 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001131 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001132 }
1133
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001134 private boolean isNetworkMeteredUnchecked(int networkType) {
1135 final NetworkState state = getNetworkStateUnchecked(networkType);
1136 if (state != null) {
1137 try {
1138 return mPolicyManager.isNetworkMetered(state);
1139 } catch (RemoteException e) {
1140 }
1141 }
1142 return false;
1143 }
1144
The Android Open Source Project28527d22009-03-03 19:31:44 -08001145 public boolean setRadios(boolean turnOn) {
1146 boolean result = true;
1147 enforceChangePermission();
1148 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001149 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001150 }
1151 return result;
1152 }
1153
1154 public boolean setRadio(int netType, boolean turnOn) {
1155 enforceChangePermission();
1156 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1157 return false;
1158 }
1159 NetworkStateTracker tracker = mNetTrackers[netType];
1160 return tracker != null && tracker.setRadio(turnOn);
1161 }
1162
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001163 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1164 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001165 public void interfaceClassDataActivityChanged(String label, boolean active) {
1166 int deviceType = Integer.parseInt(label);
1167 sendDataActivityBroadcast(deviceType, active);
1168 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001169 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001170
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001171 /**
1172 * Used to notice when the calling process dies so we can self-expire
1173 *
1174 * Also used to know if the process has cleaned up after itself when
1175 * our auto-expire timer goes off. The timer has a link to an object.
1176 *
1177 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001178 private class FeatureUser implements IBinder.DeathRecipient {
1179 int mNetworkType;
1180 String mFeature;
1181 IBinder mBinder;
1182 int mPid;
1183 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001184 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001185
1186 FeatureUser(int type, String feature, IBinder binder) {
1187 super();
1188 mNetworkType = type;
1189 mFeature = feature;
1190 mBinder = binder;
1191 mPid = getCallingPid();
1192 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001193 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001194
Robert Greenwalt2034b912009-08-12 16:08:25 -07001195 try {
1196 mBinder.linkToDeath(this, 0);
1197 } catch (RemoteException e) {
1198 binderDied();
1199 }
1200 }
1201
1202 void unlinkDeathRecipient() {
1203 mBinder.unlinkToDeath(this, 0);
1204 }
1205
1206 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001207 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001208 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1209 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001210 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001211 }
1212
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001213 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001214 if (VDBG) {
1215 log("ConnectivityService FeatureUser expire(" +
1216 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1217 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1218 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001219 stopUsingNetworkFeature(this, false);
1220 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001221
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001222 public boolean isSameUser(FeatureUser u) {
1223 if (u == null) return false;
1224
1225 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1226 }
1227
1228 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1229 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1230 TextUtils.equals(mFeature, feature)) {
1231 return true;
1232 }
1233 return false;
1234 }
1235
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001236 public String toString() {
1237 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1238 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1239 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001240 }
1241
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001242 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001243 public int startUsingNetworkFeature(int networkType, String feature,
1244 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001245 long startTime = 0;
1246 if (DBG) {
1247 startTime = SystemClock.elapsedRealtime();
1248 }
Wink Savillea7d56572011-09-21 11:05:43 -07001249 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001250 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1251 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001252 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001253 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001254 try {
1255 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1256 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001257 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001258 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001259
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001260 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001261
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001262 // TODO - move this into individual networktrackers
1263 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001264
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001265 if (mLockdownEnabled) {
1266 // Since carrier APNs usually aren't available from VPN
1267 // endpoint, mark them as unavailable.
1268 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1269 }
1270
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001271 if (mProtectedNetworks.contains(usedNetworkType)) {
1272 enforceConnectivityInternalPermission();
1273 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001274
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001275 // if UID is restricted, don't allow them to bring up metered APNs
1276 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1277 final int uidRules;
1278 synchronized (mRulesLock) {
1279 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1280 }
1281 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001282 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001283 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001284
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001285 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1286 if (network != null) {
1287 Integer currentPid = new Integer(getCallingPid());
1288 if (usedNetworkType != networkType) {
1289 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001290
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001291 if (ni.isAvailable() == false) {
1292 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1293 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001294 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001295 } else {
1296 // else make the attempt anyway - probably giving REQUEST_STARTED below
1297 if (DBG) {
1298 log("special network not available, but try anyway ni=" +
1299 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001300 }
1301 }
1302 }
1303
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001304 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001305
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001306 synchronized(this) {
1307 boolean addToList = true;
1308 if (restoreTimer < 0) {
1309 // In case there is no timer is specified for the feature,
1310 // make sure we don't add duplicate entry with the same request.
1311 for (FeatureUser u : mFeatureUsers) {
1312 if (u.isSameUser(f)) {
1313 // Duplicate user is found. Do not add.
1314 addToList = false;
1315 break;
1316 }
1317 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001318 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001319
1320 if (addToList) mFeatureUsers.add(f);
1321 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1322 // this gets used for per-pid dns when connected
1323 mNetRequestersPids[usedNetworkType].add(currentPid);
1324 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001325 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001326
1327 if (restoreTimer >= 0) {
1328 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1329 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1330 }
1331
1332 if ((ni.isConnectedOrConnecting() == true) &&
1333 !network.isTeardownRequested()) {
1334 if (ni.isConnected() == true) {
1335 final long token = Binder.clearCallingIdentity();
1336 try {
1337 // add the pid-specific dns
1338 handleDnsConfigurationChange(usedNetworkType);
1339 if (VDBG) log("special network already active");
1340 } finally {
1341 Binder.restoreCallingIdentity(token);
1342 }
Wink Saville64e3f782012-07-10 12:37:54 -07001343 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001344 }
1345 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001346 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001347 }
1348
1349 // check if the radio in play can make another contact
1350 // assume if cannot for now
1351
1352 if (DBG) {
1353 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1354 feature);
1355 }
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001356 if (network.reconnect()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001357 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001358 return PhoneConstants.APN_REQUEST_STARTED;
1359 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001360 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001361 return PhoneConstants.APN_REQUEST_FAILED;
1362 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001363 } else {
1364 // need to remember this unsupported request so we respond appropriately on stop
1365 synchronized(this) {
1366 mFeatureUsers.add(f);
1367 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1368 // this gets used for per-pid dns when connected
1369 mNetRequestersPids[usedNetworkType].add(currentPid);
1370 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001371 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001372 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001373 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001374 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001375 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001376 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
Wink Saville64e3f782012-07-10 12:37:54 -07001377 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001378 } finally {
1379 if (DBG) {
1380 final long execTime = SystemClock.elapsedRealtime() - startTime;
1381 if (execTime > 250) {
1382 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1383 } else {
1384 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1385 }
1386 }
1387 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001388 }
1389
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001390 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001391 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001392 enforceChangePermission();
1393
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001394 int pid = getCallingPid();
1395 int uid = getCallingUid();
1396
1397 FeatureUser u = null;
1398 boolean found = false;
1399
1400 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001401 for (FeatureUser x : mFeatureUsers) {
1402 if (x.isSameUser(pid, uid, networkType, feature)) {
1403 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001404 found = true;
1405 break;
1406 }
1407 }
1408 }
1409 if (found && u != null) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001410 if (VDBG) log("stopUsingNetworkFeature: X");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001411 // stop regardless of how many other time this proc had called start
1412 return stopUsingNetworkFeature(u, true);
1413 } else {
1414 // none found!
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001415 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001416 return 1;
1417 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001418 }
1419
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001420 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1421 int networkType = u.mNetworkType;
1422 String feature = u.mFeature;
1423 int pid = u.mPid;
1424 int uid = u.mUid;
1425
1426 NetworkStateTracker tracker = null;
1427 boolean callTeardown = false; // used to carry our decision outside of sync block
1428
Wink Savillea7d56572011-09-21 11:05:43 -07001429 if (VDBG) {
1430 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001431 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001432
The Android Open Source Project28527d22009-03-03 19:31:44 -08001433 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001434 if (DBG) {
1435 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1436 ", net is invalid");
1437 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001438 return -1;
1439 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001440
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001441 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1442 // sync block
1443 synchronized(this) {
1444 // check if this process still has an outstanding start request
1445 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001446 if (VDBG) {
1447 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1448 ", ignoring");
1449 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001450 return 1;
1451 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001452 u.unlinkDeathRecipient();
1453 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1454 // If we care about duplicate requests, check for that here.
1455 //
1456 // This is done to support the extension of a request - the app
1457 // can request we start the network feature again and renew the
1458 // auto-shutoff delay. Normal "stop" calls from the app though
1459 // do not pay attention to duplicate requests - in effect the
1460 // API does not refcount and a single stop will counter multiple starts.
1461 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001462 for (FeatureUser x : mFeatureUsers) {
1463 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001464 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001465 return 1;
1466 }
1467 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001468 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001469
repo syncf5de5572011-07-29 23:55:49 -07001470 // TODO - move to individual network trackers
1471 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1472
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001473 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001474 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001475 if (DBG) {
1476 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1477 " no known tracker for used net type " + usedNetworkType);
1478 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001479 return -1;
1480 }
1481 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001482 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001483 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalte767d812013-02-12 17:18:25 -08001484
1485 final long token = Binder.clearCallingIdentity();
1486 try {
1487 reassessPidDns(pid, true);
1488 } finally {
1489 Binder.restoreCallingIdentity(token);
1490 }
Mattias Falkd697aa22011-08-23 14:15:13 +02001491 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001492 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001493 if (VDBG) {
1494 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1495 " others still using it");
1496 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001497 return 1;
1498 }
1499 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001500 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001501 if (DBG) {
1502 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1503 " not a known feature - dropping");
1504 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001505 }
1506 }
Wink Savillea7d56572011-09-21 11:05:43 -07001507
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001508 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001509 if (DBG) {
1510 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1511 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001512 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001513 return 1;
1514 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001515 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001516 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001517 }
1518
1519 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001520 * @deprecated use requestRouteToHostAddress instead
1521 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001522 * Ensure that a network route exists to deliver traffic to the specified
1523 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001524 * @param networkType the type of the network over which traffic to the
1525 * specified host is to be routed
1526 * @param hostAddress the IP address of the host to which the route is
1527 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001528 * @return {@code true} on success, {@code false} on failure
1529 */
1530 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001531 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1532
1533 if (inetAddress == null) {
1534 return false;
1535 }
1536
1537 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1538 }
1539
1540 /**
1541 * Ensure that a network route exists to deliver traffic to the specified
1542 * host via the specified network interface.
1543 * @param networkType the type of the network over which traffic to the
1544 * specified host is to be routed
1545 * @param hostAddress the IP address of the host to which the route is
1546 * desired
1547 * @return {@code true} on success, {@code false} on failure
1548 */
1549 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001550 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001551 if (mProtectedNetworks.contains(networkType)) {
1552 enforceConnectivityInternalPermission();
1553 }
1554
The Android Open Source Project28527d22009-03-03 19:31:44 -08001555 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001556 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001557 return false;
1558 }
1559 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001560 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001561
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001562 if (tracker == null || (netState != DetailedState.CONNECTED &&
1563 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001564 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001565 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07001566 log("requestRouteToHostAddress on down network "
1567 + "(" + networkType + ") - dropped"
1568 + " tracker=" + tracker
1569 + " netState=" + netState
1570 + " isTeardownRequested="
1571 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001572 }
1573 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001574 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001575 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001576 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001577 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001578 LinkProperties lp = tracker.getLinkProperties();
Chad Brubaker49db4222013-07-15 16:34:04 -07001579 boolean ok = addRouteToAddress(lp, addr, EXEMPT);
Wink Saville32506bc2013-06-29 21:10:57 -07001580 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1581 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001582 } catch (UnknownHostException e) {
1583 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1584 } finally {
1585 Binder.restoreCallingIdentity(token);
1586 }
Wink Saville32506bc2013-06-29 21:10:57 -07001587 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001588 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001589 }
1590
Chad Brubaker49db4222013-07-15 16:34:04 -07001591 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1592 boolean exempt) {
1593 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001594 }
1595
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001596 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001597 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001598 }
1599
Chad Brubaker49db4222013-07-15 16:34:04 -07001600 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1601 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001602 }
1603
1604 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001605 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
Robert Greenwalt98107422011-07-22 11:55:33 -07001606 }
1607
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001608 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
Chad Brubaker49db4222013-07-15 16:34:04 -07001609 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001610 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001611 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001612 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001613 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001614 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001615 if (bestRoute.getGateway().equals(addr)) {
1616 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001617 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001618 } else {
1619 // if we will connect to this through another route, add a direct route
1620 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001621 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001622 }
1623 }
Chad Brubaker49db4222013-07-15 16:34:04 -07001624 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001625 }
1626
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001627 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
Chad Brubaker49db4222013-07-15 16:34:04 -07001628 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001629 if ((lp == null) || (r == null)) {
1630 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001631 return false;
1632 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001633
1634 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001635 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001636 return false;
1637 }
1638
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001639 String ifaceName = r.getInterface();
1640 if(ifaceName == null) {
1641 loge("Error modifying route - no interface name");
1642 return false;
1643 }
Robert Greenwalt59070cf2013-04-11 13:48:16 -07001644 if (r.hasGateway()) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001645 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001646 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001647 if (bestRoute.getGateway().equals(r.getGateway())) {
1648 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001649 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001650 } else {
1651 // if we will connect to our gateway through another route, add a direct
1652 // route to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001653 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1654 bestRoute.getGateway(),
1655 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001656 }
Chad Brubaker49db4222013-07-15 16:34:04 -07001657 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001658 }
1659 }
1660 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001661 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001662 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001663 if (toDefaultTable) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001664 synchronized (mRoutesLock) {
1665 // only track default table - only one apps can effect
1666 mAddedRoutes.add(r);
1667 mNetd.addRoute(ifaceName, r);
1668 if (exempt) {
1669 LinkAddress dest = r.getDestination();
1670 if (!mExemptAddresses.contains(dest)) {
1671 mNetd.setHostExemption(dest);
1672 mExemptAddresses.add(dest);
1673 }
1674 }
1675 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001676 } else {
1677 mNetd.addSecondaryRoute(ifaceName, r);
1678 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001679 } catch (Exception e) {
1680 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001681 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001682 return false;
1683 }
1684 } else {
1685 // if we remove this one and there are no more like it, then refcount==0 and
1686 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001687 if (toDefaultTable) {
Chad Brubaker49db4222013-07-15 16:34:04 -07001688 synchronized (mRoutesLock) {
1689 mAddedRoutes.remove(r);
1690 if (mAddedRoutes.contains(r) == false) {
1691 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1692 try {
1693 mNetd.removeRoute(ifaceName, r);
1694 LinkAddress dest = r.getDestination();
1695 if (mExemptAddresses.contains(dest)) {
1696 mNetd.clearHostExemption(dest);
1697 mExemptAddresses.remove(dest);
1698 }
1699 } catch (Exception e) {
1700 // never crash - catch them all
1701 if (VDBG) loge("Exception trying to remove a route: " + e);
1702 return false;
1703 }
1704 } else {
1705 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001706 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001707 }
1708 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001709 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001710 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001711 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001712 } catch (Exception e) {
1713 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001714 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001715 return false;
1716 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001717 }
1718 }
1719 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001720 }
1721
1722 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001723 * @see ConnectivityManager#getMobileDataEnabled()
1724 */
1725 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001726 // TODO: This detail should probably be in DataConnectionTracker's
1727 // which is where we store the value and maybe make this
1728 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001729 enforceAccessPermission();
Jeff Sharkey8b361572012-09-26 15:54:06 -07001730 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1731 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001732 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001733 return retVal;
1734 }
1735
Robert Greenwalt34848c02011-03-25 13:09:25 -07001736 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001737 enforceConnectivityInternalPermission();
1738
Robert Greenwalt34848c02011-03-25 13:09:25 -07001739 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1740 (met ? ENABLED : DISABLED), networkType));
1741 }
1742
1743 private void handleSetDependencyMet(int networkType, boolean met) {
1744 if (mNetTrackers[networkType] != null) {
1745 if (DBG) {
1746 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1747 }
1748 mNetTrackers[networkType].setDependencyMet(met);
1749 }
1750 }
1751
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001752 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1753 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001754 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001755 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001756 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001757 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001758 }
1759
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001760 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001761 // skip update when we've already applied rules
1762 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1763 if (oldRules == uidRules) return;
1764
1765 mUidRules.put(uid, uidRules);
1766 }
1767
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001768 // TODO: notify UID when it has requested targeted updates
1769 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001770
1771 @Override
1772 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001773 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001774 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001775 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001776 }
1777
1778 synchronized (mRulesLock) {
1779 mMeteredIfaces.clear();
1780 for (String iface : meteredIfaces) {
1781 mMeteredIfaces.add(iface);
1782 }
1783 }
1784 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001785
1786 @Override
1787 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1788 // caller is NPMS, since we only register with them
1789 if (LOGD_RULES) {
1790 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1791 }
1792
1793 // kick off connectivity change broadcast for active network, since
1794 // global background policy change is radical.
1795 final int networkType = mActiveDefaultNetwork;
1796 if (isNetworkTypeValid(networkType)) {
1797 final NetworkStateTracker tracker = mNetTrackers[networkType];
1798 if (tracker != null) {
1799 final NetworkInfo info = tracker.getNetworkInfo();
1800 if (info != null && info.isConnected()) {
1801 sendConnectedBroadcast(info);
1802 }
1803 }
1804 }
1805 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001806 };
1807
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001808 /**
1809 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1810 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001811 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001812 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001813 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001814
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001815 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001816 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001817 }
1818
1819 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001820 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001821 if (VDBG) {
1822 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001823 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001824 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1825 }
tk.mun5eee1042012-01-06 10:43:52 +09001826 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1827 if (VDBG) {
1828 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1829 }
1830 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1831 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001832 }
1833
1834 @Override
1835 public void setPolicyDataEnable(int networkType, boolean enabled) {
1836 // only someone like NPMS should only be calling us
1837 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1838
1839 mHandler.sendMessage(mHandler.obtainMessage(
1840 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1841 }
1842
1843 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1844 if (isNetworkTypeValid(networkType)) {
1845 final NetworkStateTracker tracker = mNetTrackers[networkType];
1846 if (tracker != null) {
1847 tracker.setPolicyDataEnable(enabled);
1848 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001849 }
1850 }
1851
The Android Open Source Project28527d22009-03-03 19:31:44 -08001852 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001853 mContext.enforceCallingOrSelfPermission(
1854 android.Manifest.permission.ACCESS_NETWORK_STATE,
1855 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001856 }
1857
1858 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001859 mContext.enforceCallingOrSelfPermission(
1860 android.Manifest.permission.CHANGE_NETWORK_STATE,
1861 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001862 }
1863
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001864 // TODO Make this a special check when it goes public
1865 private void enforceTetherChangePermission() {
1866 mContext.enforceCallingOrSelfPermission(
1867 android.Manifest.permission.CHANGE_NETWORK_STATE,
1868 "ConnectivityService");
1869 }
1870
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001871 private void enforceTetherAccessPermission() {
1872 mContext.enforceCallingOrSelfPermission(
1873 android.Manifest.permission.ACCESS_NETWORK_STATE,
1874 "ConnectivityService");
1875 }
1876
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001877 private void enforceConnectivityInternalPermission() {
1878 mContext.enforceCallingOrSelfPermission(
1879 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1880 "ConnectivityService");
1881 }
1882
Chad Brubaker11f22252013-07-11 13:29:30 -07001883 private void enforceMarkNetworkSocketPermission() {
1884 //Media server special case
1885 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1886 return;
1887 }
1888 mContext.enforceCallingOrSelfPermission(
1889 android.Manifest.permission.MARK_NETWORK_SOCKET,
1890 "ConnectivityService");
1891 }
1892
The Android Open Source Project28527d22009-03-03 19:31:44 -08001893 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001894 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1895 * network, we ignore it. If it is for the active network, we send out a
1896 * broadcast. But first, we check whether it might be possible to connect
1897 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001898 * @param info the {@code NetworkInfo} for the network
1899 */
1900 private void handleDisconnect(NetworkInfo info) {
1901
Robert Greenwalt2034b912009-08-12 16:08:25 -07001902 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001903
Robert Greenwalt2034b912009-08-12 16:08:25 -07001904 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Baie2462442012-06-28 15:26:19 -07001905
1906 // Remove idletimer previously setup in {@code handleConnect}
1907 removeDataActivityTracking(prevNetType);
1908
The Android Open Source Project28527d22009-03-03 19:31:44 -08001909 /*
1910 * If the disconnected network is not the active one, then don't report
1911 * this as a loss of connectivity. What probably happened is that we're
1912 * getting the disconnect for a network that we explicitly disabled
1913 * in accordance with network preference policies.
1914 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001915 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkd697aa22011-08-23 14:15:13 +02001916 List<Integer> pids = mNetRequestersPids[prevNetType];
1917 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001918 // will remove them because the net's no longer connected
1919 // need to do this now as only now do we know the pids and
1920 // can properly null things that are no longer referenced.
1921 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001922 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001923 }
1924
The Android Open Source Project28527d22009-03-03 19:31:44 -08001925 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001926 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001927 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001928 if (info.isFailover()) {
1929 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1930 info.setFailover(false);
1931 }
1932 if (info.getReason() != null) {
1933 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1934 }
1935 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001936 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1937 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001938 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001939
Robert Greenwalt34848c02011-03-25 13:09:25 -07001940 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001941 tryFailover(prevNetType);
1942 if (mActiveDefaultNetwork != -1) {
1943 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001944 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1945 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001946 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001947 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1948 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001949 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001950 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001951
1952 // Reset interface if no other connections are using the same interface
1953 boolean doReset = true;
1954 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1955 if (linkProperties != null) {
1956 String oldIface = linkProperties.getInterfaceName();
1957 if (TextUtils.isEmpty(oldIface) == false) {
1958 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1959 if (networkStateTracker == null) continue;
1960 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1961 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1962 LinkProperties l = networkStateTracker.getLinkProperties();
1963 if (l == null) continue;
1964 if (oldIface.equals(l.getInterfaceName())) {
1965 doReset = false;
1966 break;
1967 }
1968 }
1969 }
1970 }
1971 }
1972
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001973 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001974 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001975
Jeff Sharkey971cd162011-08-29 16:02:57 -07001976 final Intent immediateIntent = new Intent(intent);
1977 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1978 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001979 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001980 /*
1981 * If the failover network is already connected, then immediately send
1982 * out a followup broadcast indicating successful failover
1983 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001984 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001985 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1986 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001987 }
1988 }
1989
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001990 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001991 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001992 * If this is a default network, check if other defaults are available.
1993 * Try to reconnect on all available and let them hash it out when
1994 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001995 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001996 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001997 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07001998 if (DBG) {
1999 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2000 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002001 mActiveDefaultNetwork = -1;
2002 }
2003
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002004 // don't signal a reconnect for anything lower or equal priority than our
2005 // current connected default
2006 // TODO - don't filter by priority now - nice optimization but risky
2007// int currentPriority = -1;
2008// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002009// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002010// }
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002011
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002012 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07002013 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002014 if (mNetConfigs[checkType] == null) continue;
2015 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08002016 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08002017
2018// Enabling the isAvailable() optimization caused mobile to not get
2019// selected if it was in the middle of error handling. Specifically
2020// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2021// would not be available and we wouldn't get connected to anything.
2022// So removing the isAvailable() optimization below for now. TODO: This
2023// optimization should work and we need to investigate why it doesn't work.
2024// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2025// complete before it is really complete.
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002026
Wink Saville72a95b92011-01-26 15:43:49 -08002027// if (!mNetTrackers[checkType].isAvailable()) continue;
2028
Robert Greenwalt34848c02011-03-25 13:09:25 -07002029// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002030
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002031 NetworkStateTracker checkTracker = mNetTrackers[checkType];
2032 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2033 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2034 checkInfo.setFailover(true);
2035 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002036 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002037 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002038 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002039 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002040 }
2041
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002042 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002043 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07002044 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2045 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002046 }
2047
Wink Saville4f0de1e2011-08-04 15:01:58 -07002048 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002049 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2050 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002051 }
2052
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002053 private void sendInetConditionBroadcast(NetworkInfo info) {
2054 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2055 }
2056
Wink Saville4f0de1e2011-08-04 15:01:58 -07002057 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002058 if (mLockdownTracker != null) {
2059 info = mLockdownTracker.augmentNetworkInfo(info);
2060 }
2061
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002062 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002063 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002064 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002065 if (info.isFailover()) {
2066 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2067 info.setFailover(false);
2068 }
2069 if (info.getReason() != null) {
2070 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2071 }
2072 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002073 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2074 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002075 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002076 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002077 return intent;
2078 }
2079
2080 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2081 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2082 }
2083
2084 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2085 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002086 }
2087
Haoyu Baib5da5752012-06-20 14:29:57 -07002088 private void sendDataActivityBroadcast(int deviceType, boolean active) {
2089 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2090 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2091 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002092 final long ident = Binder.clearCallingIdentity();
2093 try {
2094 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2095 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2096 } finally {
2097 Binder.restoreCallingIdentity(ident);
2098 }
Haoyu Baib5da5752012-06-20 14:29:57 -07002099 }
2100
The Android Open Source Project28527d22009-03-03 19:31:44 -08002101 /**
2102 * Called when an attempt to fail over to another network has failed.
2103 * @param info the {@link NetworkInfo} for the failed network
2104 */
2105 private void handleConnectionFailure(NetworkInfo info) {
2106 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002107
Robert Greenwalt2034b912009-08-12 16:08:25 -07002108 String reason = info.getReason();
2109 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07002110
Robert Greenwalte981bc52010-10-08 16:35:52 -07002111 String reasonText;
2112 if (reason == null) {
2113 reasonText = ".";
2114 } else {
2115 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08002116 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002117 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002118
2119 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002120 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002121 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002122 if (getActiveNetworkInfo() == null) {
2123 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2124 }
2125 if (reason != null) {
2126 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2127 }
2128 if (extraInfo != null) {
2129 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2130 }
2131 if (info.isFailover()) {
2132 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2133 info.setFailover(false);
2134 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002135
Robert Greenwalt34848c02011-03-25 13:09:25 -07002136 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002137 tryFailover(info.getType());
2138 if (mActiveDefaultNetwork != -1) {
2139 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002140 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2141 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002142 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002143 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2144 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002145 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002146
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002147 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002148
2149 final Intent immediateIntent = new Intent(intent);
2150 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2151 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002152 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002153 /*
2154 * If the failover network is already connected, then immediately send
2155 * out a followup broadcast indicating successful failover
2156 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002157 if (mActiveDefaultNetwork != -1) {
2158 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002159 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002160 }
2161
2162 private void sendStickyBroadcast(Intent intent) {
2163 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002164 if (!mSystemReady) {
2165 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002166 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002167 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002168 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002169 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002170 }
2171
Dianne Hackborne588ca12012-09-04 18:48:37 -07002172 final long ident = Binder.clearCallingIdentity();
2173 try {
2174 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2175 } finally {
2176 Binder.restoreCallingIdentity(ident);
2177 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002178 }
2179 }
2180
Wink Saville4f0de1e2011-08-04 15:01:58 -07002181 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2182 if (delayMs <= 0) {
2183 sendStickyBroadcast(intent);
2184 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002185 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002186 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2187 + intent.getAction());
2188 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002189 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2190 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2191 }
2192 }
2193
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002194 void systemReady() {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002195 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2196 loadGlobalProxy();
2197
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002198 synchronized(this) {
2199 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002200 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002201 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002202 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002203 }
2204 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002205 // load the global proxy at startup
2206 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002207
2208 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2209 // for user to unlock device.
2210 if (!updateLockdownVpn()) {
2211 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2212 mContext.registerReceiver(mUserPresentReceiver, filter);
2213 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002214 }
2215
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002216 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2217 @Override
2218 public void onReceive(Context context, Intent intent) {
2219 // Try creating lockdown tracker, since user present usually means
2220 // unlocked keystore.
2221 if (updateLockdownVpn()) {
2222 mContext.unregisterReceiver(this);
2223 }
2224 }
2225 };
2226
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002227 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002228 if (((type != mNetworkPreference)
2229 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2230 || (mNetworkPreference == mActiveDefaultNetwork)) {
2231 return false;
2232 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002233 return true;
2234 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002235
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002236 private void handleConnect(NetworkInfo info) {
2237 final int newNetType = info.getType();
2238
2239 setupDataActivityTracking(newNetType);
Haoyu Baie2462442012-06-28 15:26:19 -07002240
The Android Open Source Project28527d22009-03-03 19:31:44 -08002241 // snapshot isFailover, because sendConnectedBroadcast() resets it
2242 boolean isFailover = info.isFailover();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002243 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002244 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002245
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002246 if (VDBG) {
2247 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2248 + " isFailover" + isFailover);
2249 }
2250
Robert Greenwalt2034b912009-08-12 16:08:25 -07002251 // if this is a default net and other default is running
2252 // kill the one not preferred
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002253 if (mNetConfigs[newNetType].isDefault()) {
2254 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2255 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002256 // tear down the other
2257 NetworkStateTracker otherNet =
2258 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002259 if (DBG) {
2260 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002261 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002262 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002263 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002264 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002265 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002266 return;
2267 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002268 } else {
2269 // don't accept this one
2270 if (VDBG) {
2271 log("Not broadcasting CONNECT_ACTION " +
2272 "to torn down network " + info.getTypeName());
2273 }
2274 teardown(thisNet);
2275 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002276 }
2277 }
2278 synchronized (ConnectivityService.this) {
2279 // have a new default network, release the transition wakelock in a second
2280 // if it's held. The second pause is to allow apps to reconnect over the
2281 // new network
2282 if (mNetTransitionWakeLock.isHeld()) {
2283 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002284 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002285 mNetTransitionWakeLockSerialNumber, 0),
2286 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002287 }
2288 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002289 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002290 // this will cause us to come up initially as unconnected and switching
2291 // to connected after our normal pause unless somebody reports us as reall
2292 // disconnected
2293 mDefaultInetConditionPublished = 0;
2294 mDefaultConnectionSequence++;
2295 mInetConditionChangeInFlight = false;
2296 // Don't do this - if we never sign in stay, grey
2297 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002298 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002299 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002300 updateNetworkSettings(thisNet);
sy.yun4aa73922013-09-02 05:24:09 +09002301 updateMtuSizeSettings(thisNet);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002302 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002303 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002304
2305 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002306 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002307 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002308 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002309 } catch (RemoteException e) {
2310 // ignored; service lives in system_server
2311 }
2312 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002313 }
2314
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002315 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2316 if (DBG) log("Captive portal check " + info);
2317 int type = info.getType();
2318 final NetworkStateTracker thisNet = mNetTrackers[type];
2319 if (mNetConfigs[type].isDefault()) {
2320 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2321 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2322 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002323 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002324 return;
2325 } else {
2326 if (DBG) log("Tear down low priority net " + info.getTypeName());
2327 teardown(thisNet);
2328 return;
2329 }
2330 }
2331 }
2332
Wink Saville674777e2013-08-07 16:22:47 -07002333 if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002334 thisNet.captivePortalCheckComplete();
2335 }
2336
2337 /** @hide */
Wink Saville674777e2013-08-07 16:22:47 -07002338 @Override
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002339 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002340 enforceConnectivityInternalPermission();
Wink Saville674777e2013-08-07 16:22:47 -07002341 if (DBG) log("captivePortalCheckComplete: ni=" + info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002342 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002343 }
2344
Wink Saville674777e2013-08-07 16:22:47 -07002345 /** @hide */
2346 @Override
2347 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2348 enforceConnectivityInternalPermission();
2349 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2350 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2351 }
2352
The Android Open Source Project28527d22009-03-03 19:31:44 -08002353 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002354 * Setup data activity tracking for the given network interface.
2355 *
2356 * Every {@code setupDataActivityTracking} should be paired with a
2357 * {@link removeDataActivityTracking} for cleanup.
2358 */
2359 private void setupDataActivityTracking(int type) {
2360 final NetworkStateTracker thisNet = mNetTrackers[type];
2361 final String iface = thisNet.getLinkProperties().getInterfaceName();
2362
2363 final int timeout;
2364
2365 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002366 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2367 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Baie2462442012-06-28 15:26:19 -07002368 0);
2369 // Canonicalize mobile network type
2370 type = ConnectivityManager.TYPE_MOBILE;
2371 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002372 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2373 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Baie2462442012-06-28 15:26:19 -07002374 0);
2375 } else {
2376 // do not track any other networks
2377 timeout = 0;
2378 }
2379
2380 if (timeout > 0 && iface != null) {
2381 try {
2382 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2383 } catch (RemoteException e) {
2384 }
2385 }
2386 }
2387
2388 /**
2389 * Remove data activity tracking when network disconnects.
2390 */
2391 private void removeDataActivityTracking(int type) {
2392 final NetworkStateTracker net = mNetTrackers[type];
2393 final String iface = net.getLinkProperties().getInterfaceName();
2394
2395 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2396 ConnectivityManager.TYPE_WIFI == type)) {
2397 try {
2398 // the call fails silently if no idletimer setup for this interface
2399 mNetd.removeIdleTimer(iface);
2400 } catch (RemoteException e) {
2401 }
2402 }
2403 }
2404
2405 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002406 * After a change in the connectivity state of a network. We're mainly
2407 * concerned with making sure that the list of DNS servers is set up
2408 * according to which networks are connected, and ensuring that the
2409 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002410 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002411 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002412 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubaker49db4222013-07-15 16:34:04 -07002413 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002414 if (VDBG) {
2415 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2416 + " resetMask=" + resetMask);
2417 }
Wink Saville051a6642011-07-13 13:44:13 -07002418
The Android Open Source Project28527d22009-03-03 19:31:44 -08002419 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002420 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002421 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002422 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002423 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002424
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002425 LinkProperties curLp = mCurrentLinkProperties[netType];
2426 LinkProperties newLp = null;
2427
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002428 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002429 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002430 if (VDBG) {
2431 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2432 " doReset=" + doReset + " resetMask=" + resetMask +
2433 "\n curLp=" + curLp +
2434 "\n newLp=" + newLp);
2435 }
2436
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002437 if (curLp != null) {
2438 if (curLp.isIdenticalInterfaceName(newLp)) {
2439 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2440 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2441 for (LinkAddress linkAddr : car.removed) {
2442 if (linkAddr.getAddress() instanceof Inet4Address) {
2443 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2444 }
2445 if (linkAddr.getAddress() instanceof Inet6Address) {
2446 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2447 }
Wink Saville051a6642011-07-13 13:44:13 -07002448 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002449 if (DBG) {
2450 log("handleConnectivityChange: addresses changed" +
2451 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2452 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002453 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002454 } else {
2455 if (DBG) {
2456 log("handleConnectivityChange: address are the same reset per doReset" +
2457 " linkProperty[" + netType + "]:" +
2458 " resetMask=" + resetMask);
2459 }
Wink Saville051a6642011-07-13 13:44:13 -07002460 }
2461 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002462 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002463 if (DBG) {
2464 log("handleConnectivityChange: interface not not equivalent reset both" +
2465 " linkProperty[" + netType + "]:" +
2466 " resetMask=" + resetMask);
2467 }
Wink Saville051a6642011-07-13 13:44:13 -07002468 }
Wink Saville051a6642011-07-13 13:44:13 -07002469 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002470 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002471 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002472 }
2473 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002474 if (VDBG) {
2475 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2476 " doReset=" + doReset + " resetMask=" + resetMask +
2477 "\n curLp=" + curLp +
2478 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002479 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002480 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002481 mCurrentLinkProperties[netType] = newLp;
Chad Brubaker49db4222013-07-15 16:34:04 -07002482 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002483
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002484 if (resetMask != 0 || resetDns) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002485 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwalt4398f342013-05-23 18:33:06 -07002486 if (curLp != null) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002487 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwalt4398f342013-05-23 18:33:06 -07002488 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti63839822013-03-20 19:22:58 +09002489 if (TextUtils.isEmpty(iface) == false) {
2490 if (resetMask != 0) {
2491 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2492 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002493
Lorenzo Colitti63839822013-03-20 19:22:58 +09002494 // Tell VPN the interface is down. It is a temporary
2495 // but effective fix to make VPN aware of the change.
2496 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07002497 synchronized(mVpns) {
2498 for (int i = 0; i < mVpns.size(); i++) {
2499 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2500 }
2501 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002502 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002503 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002504 if (resetDns) {
2505 flushVmDnsCache();
2506 if (VDBG) log("resetting DNS cache for " + iface);
2507 try {
2508 mNetd.flushInterfaceDnsCache(iface);
2509 } catch (Exception e) {
2510 // never crash - catch them all
2511 if (DBG) loge("Exception resetting dns cache: " + e);
2512 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002513 }
Robert Greenwalt4398f342013-05-23 18:33:06 -07002514 } else {
2515 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002516 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002517 }
2518 }
2519 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002520
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002521 // Update 464xlat state.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002522 NetworkStateTracker tracker = mNetTrackers[netType];
2523 if (mClat.requiresClat(netType, tracker)) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002524
Lorenzo Colitti4118d082013-03-28 14:13:43 +09002525 // If the connection was previously using clat, but is not using it now, stop the clat
2526 // daemon. Normally, this happens automatically when the connection disconnects, but if
2527 // the disconnect is not reported, or if the connection's LinkProperties changed for
2528 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2529 // still be running. If it's not running, then stopping it is a no-op.
2530 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2531 mClat.stopClat();
2532 }
2533 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002534 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2535 mClat.startClat(tracker);
2536 } else {
2537 mClat.stopClat();
2538 }
2539 }
2540
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002541 // TODO: Temporary notifying upstread change to Tethering.
2542 // @see bug/4455071
2543 /** Notify TetheringService if interface name has been changed. */
2544 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002545 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002546 if (isTetheringSupported()) {
2547 mTethering.handleTetherIfaceChange();
2548 }
2549 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002550 }
2551
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002552 /**
2553 * Add and remove routes using the old properties (null if not previously connected),
2554 * new properties (null if becoming disconnected). May even be double null, which
2555 * is a noop.
2556 * Uses isLinkDefault to determine if default routes should be set or conversely if
2557 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002558 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002559 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002560 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubaker49db4222013-07-15 16:34:04 -07002561 boolean isLinkDefault, boolean exempt) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002562 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002563 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2564 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002565 if (curLp != null) {
2566 // check for the delta between the current set and the new
Lorenzo Colittie1b47422013-07-31 23:23:21 +09002567 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002568 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002569 } else if (newLp != null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002570 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002571 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002572 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002573
Robert Greenwalt8d777252011-08-15 12:31:55 -07002574 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2575
Robert Greenwalt98107422011-07-22 11:55:33 -07002576 for (RouteInfo r : routeDiff.removed) {
2577 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002578 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002579 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2580 }
2581 if (isLinkDefault == false) {
2582 // remove from a secondary route table
2583 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002584 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002585 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002586
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002587 if (!isLinkDefault) {
2588 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002589 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002590 // routes changed - remove all old dns entries and add new
2591 if (curLp != null) {
2592 for (InetAddress oldDns : curLp.getDnses()) {
2593 removeRouteToAddress(curLp, oldDns);
2594 }
2595 }
2596 if (newLp != null) {
2597 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002598 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07002599 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002600 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002601 } else {
2602 // no change in routes, check for change in dns themselves
2603 for (InetAddress oldDns : dnsDiff.removed) {
2604 removeRouteToAddress(curLp, oldDns);
2605 }
2606 for (InetAddress newDns : dnsDiff.added) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002607 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002608 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002609 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002610 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002611
2612 for (RouteInfo r : routeDiff.added) {
2613 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubaker49db4222013-07-15 16:34:04 -07002614 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002615 } else {
2616 // add to a secondary route table
Chad Brubaker49db4222013-07-15 16:34:04 -07002617 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002618
2619 // many radios add a default route even when we don't want one.
2620 // remove the default route unless somebody else has asked for it
2621 String ifaceName = newLp.getInterfaceName();
Chad Brubaker49db4222013-07-15 16:34:04 -07002622 synchronized (mRoutesLock) {
2623 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2624 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2625 try {
2626 mNetd.removeRoute(ifaceName, r);
2627 } catch (Exception e) {
2628 // never crash - catch them all
2629 if (DBG) loge("Exception trying to remove a route: " + e);
2630 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002631 }
2632 }
2633 }
2634 }
2635
Robert Greenwalt8d777252011-08-15 12:31:55 -07002636 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002637 }
2638
sy.yun4aa73922013-09-02 05:24:09 +09002639 /**
2640 * Reads the network specific MTU size from reources.
2641 * and set it on it's iface.
2642 */
2643 private void updateMtuSizeSettings(NetworkStateTracker nt) {
2644 final String iface = nt.getLinkProperties().getInterfaceName();
2645 final int mtu = nt.getLinkProperties().getMtu();
2646
2647 if (mtu < 68 || mtu > 10000) {
2648 loge("Unexpected mtu value: " + nt);
2649 return;
2650 }
2651
2652 try {
2653 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2654 mNetd.setMtu(iface, mtu);
2655 } catch (Exception e) {
2656 Slog.e(TAG, "exception in setMtu()" + e);
2657 }
2658 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002659
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002660 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002661 * Reads the network specific TCP buffer sizes from SystemProperties
2662 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2663 * wide use
2664 */
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002665 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002666 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002667 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002668
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002669 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002670 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002671
2672 // Setting to default values so we won't be stuck to previous values
2673 key = "net.tcp.buffersize.default";
2674 bufferSizes = SystemProperties.get(key);
2675 }
2676
2677 // Set values in kernel
2678 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002679 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002680 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002681 + "] which comes from [" + key + "]");
2682 }
2683 setBufferSize(bufferSizes);
2684 }
2685 }
2686
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07002687 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002688 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2689 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2690 *
2691 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2692 * writeMin, writeInitial, writeMax"
2693 */
2694 private void setBufferSize(String bufferSizes) {
2695 try {
2696 String[] values = bufferSizes.split(",");
2697
2698 if (values.length == 6) {
2699 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002700 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2701 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2702 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2703 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2704 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2705 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002706 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002707 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002708 }
2709 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002710 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002711 }
2712 }
2713
Robert Greenwalt2034b912009-08-12 16:08:25 -07002714 /**
2715 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2716 * on the highest priority active net which this process requested.
2717 * If there aren't any, clear it out
2718 */
Mattias Falkd697aa22011-08-23 14:15:13 +02002719 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002720 {
Mattias Falkd697aa22011-08-23 14:15:13 +02002721 if (VDBG) log("reassessPidDns for pid " + pid);
2722 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002723 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002724 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002725 continue;
2726 }
2727 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002728 if (nt.getNetworkInfo().isConnected() &&
2729 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002730 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002731 if (p == null) continue;
Mattias Falkd697aa22011-08-23 14:15:13 +02002732 if (mNetRequestersPids[i].contains(myPid)) {
2733 try {
2734 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2735 } catch (Exception e) {
2736 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002737 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002738 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002739 }
2740 }
2741 }
2742 // nothing found - delete
Mattias Falkd697aa22011-08-23 14:15:13 +02002743 try {
2744 mNetd.clearDnsInterfaceForPid(pid);
2745 } catch (Exception e) {
2746 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002747 }
2748 }
2749
Mattias Falkd697aa22011-08-23 14:15:13 +02002750 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002751 /*
2752 * Tell the VMs to toss their DNS caches
2753 */
2754 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2755 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002756 /*
2757 * Connectivity events can happen before boot has completed ...
2758 */
2759 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002760 final long ident = Binder.clearCallingIdentity();
2761 try {
2762 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2763 } finally {
2764 Binder.restoreCallingIdentity(ident);
2765 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002766 }
2767
Chia-chi Yehcc844502011-07-14 18:01:57 -07002768 // Caller must grab mDnsLock.
Mattias Falkd697aa22011-08-23 14:15:13 +02002769 private void updateDnsLocked(String network, String iface,
Chad Brubaker73652d02013-07-23 17:13:36 -07002770 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002771 int last = 0;
2772 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002773 dnses = new ArrayList();
2774 dnses.add(mDefaultDns);
2775 if (DBG) {
2776 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002777 }
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002778 }
2779
Mattias Falkd697aa22011-08-23 14:15:13 +02002780 try {
2781 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker73652d02013-07-23 17:13:36 -07002782 if (defaultDns) {
2783 mNetd.setDefaultInterfaceForDns(iface);
2784 }
2785
Robert Greenwalte41e3b32013-02-11 15:25:10 -08002786 for (InetAddress dns : dnses) {
2787 ++last;
2788 String key = "net.dns" + last;
2789 String value = dns.getHostAddress();
2790 SystemProperties.set(key, value);
2791 }
2792 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2793 String key = "net.dns" + i;
2794 SystemProperties.set(key, "");
2795 }
2796 mNumDnsEntries = last;
Mattias Falkd697aa22011-08-23 14:15:13 +02002797 } catch (Exception e) {
2798 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002799 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002800 }
2801
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002802 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002803 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002804 NetworkStateTracker nt = mNetTrackers[netType];
2805 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002806 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002807 if (p == null) return;
2808 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002809 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002810 String network = nt.getNetworkInfo().getTypeName();
2811 synchronized (mDnsLock) {
Chad Brubaker5fdc1462013-07-23 17:44:41 -07002812 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002813 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002814 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002815 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002816 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltcd277852012-11-09 10:52:27 -08002817 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002818 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002819 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002820 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002821 // set per-pid dns for attached secondary nets
Mattias Falkd697aa22011-08-23 14:15:13 +02002822 List<Integer> pids = mNetRequestersPids[netType];
2823 for (Integer pid : pids) {
2824 try {
2825 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2826 } catch (Exception e) {
2827 Slog.e(TAG, "exception setting interface for pid: " + e);
2828 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002829 }
2830 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002831 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002832 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002833 }
2834
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002835 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002836 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2837 NETWORK_RESTORE_DELAY_PROP_NAME);
2838 if(restoreDefaultNetworkDelayStr != null &&
2839 restoreDefaultNetworkDelayStr.length() != 0) {
2840 try {
2841 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2842 } catch (NumberFormatException e) {
2843 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002844 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002845 // if the system property isn't set, use the value for the apn type
2846 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2847
2848 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2849 (mNetConfigs[networkType] != null)) {
2850 ret = mNetConfigs[networkType].restoreTime;
2851 }
2852 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002853 }
2854
2855 @Override
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002856 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2857 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002858 if (mContext.checkCallingOrSelfPermission(
2859 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002860 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002861 pw.println("Permission Denial: can't dump ConnectivityService " +
2862 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2863 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002864 return;
2865 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002866
2867 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002868 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002869 for (int i = 0; i < mNetTrackers.length; i++) {
2870 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002871 if (nst != null) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002872 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2873 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002874 if (nst.getNetworkInfo().isConnected()) {
2875 pw.println("Active network: " + nst.getNetworkInfo().
2876 getTypeName());
2877 }
2878 pw.println(nst.getNetworkInfo());
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002879 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002880 pw.println(nst);
2881 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002882 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002883 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002884 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002885
2886 pw.println("Network Requester Pids:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002887 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002888 for (int net : mPriorityList) {
2889 String pidString = net + ": ";
Mattias Falkd697aa22011-08-23 14:15:13 +02002890 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002891 pidString = pidString + pid.toString() + ", ";
2892 }
2893 pw.println(pidString);
2894 }
2895 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002896 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002897
2898 pw.println("FeatureUsers:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002899 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002900 for (Object requester : mFeatureUsers) {
2901 pw.println(requester.toString());
2902 }
2903 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002904 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002905
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002906 synchronized (this) {
2907 pw.println("NetworkTranstionWakeLock is currently " +
2908 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2909 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2910 }
2911 pw.println();
2912
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002913 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002914
2915 if (mInetLog != null) {
2916 pw.println();
2917 pw.println("Inet condition reports:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002918 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002919 for(int i = 0; i < mInetLog.size(); i++) {
2920 pw.println(mInetLog.get(i));
2921 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002922 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002923 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002924 }
2925
Robert Greenwalt2034b912009-08-12 16:08:25 -07002926 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002927 private class NetworkStateTrackerHandler extends Handler {
2928 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002929 super(looper);
2930 }
2931
The Android Open Source Project28527d22009-03-03 19:31:44 -08002932 @Override
2933 public void handleMessage(Message msg) {
2934 NetworkInfo info;
2935 switch (msg.what) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002936 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002937 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002938 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002939
Wink Savillea7d56572011-09-21 11:05:43 -07002940 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Savilleb1a32022013-09-05 12:02:25 -07002941 (state == NetworkInfo.State.DISCONNECTED) ||
2942 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillea7d56572011-09-21 11:05:43 -07002943 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002944 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002945 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002946 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002947
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002948 // Since mobile has the notion of a network/apn that can be used for
2949 // provisioning we need to check every time we're connected as
2950 // CaptiveProtalTracker won't detected it because DCT doesn't report it
2951 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2952 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2953 // is received by MDST and sent here as EVENT_STATE_CHANGED.
2954 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Savillef0e9c7f2013-07-16 17:16:37 -07002955 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2956 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Savilleb1a32022013-09-05 12:02:25 -07002957 && ((state == NetworkInfo.State.CONNECTED)
2958 || info.isConnectedToProvisioningNetwork())) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002959 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Savillef0e9c7f2013-07-16 17:16:37 -07002960 }
2961
Jeff Sharkey876ddc92012-11-09 15:57:02 -08002962 EventLogTags.writeConnectivityStateChanged(
2963 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002964
2965 if (info.getDetailedState() ==
2966 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002967 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002968 } else if (info.getDetailedState() ==
2969 DetailedState.CAPTIVE_PORTAL_CHECK) {
2970 handleCaptivePortalTrackerCheck(info);
Wink Savilleb1a32022013-09-05 12:02:25 -07002971 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002972 /**
2973 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2974 * for now its an in between network, its a network that
2975 * is actually a default network but we don't want it to be
2976 * announced as such to keep background applications from
2977 * trying to use it. It turns out that some still try so we
2978 * take the additional step of clearing any default routes
2979 * to the link that may have incorrectly setup by the lower
2980 * levels.
2981 */
2982 LinkProperties lp = getLinkProperties(info.getType());
2983 if (DBG) {
2984 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2985 }
2986
2987 // Clear any default routes setup by the radio so
2988 // any activity by applications trying to use this
2989 // connection will fail until the provisioning network
2990 // is enabled.
2991 for (RouteInfo r : lp.getRoutes()) {
2992 removeRoute(lp, r, TO_DEFAULT_TABLE);
2993 }
Robert Greenwalt12c44552009-12-07 11:33:18 -08002994 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002995 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002996 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002997 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002998 // the logic here is, handle SUSPENDED the same as
2999 // DISCONNECTED. The only difference being we are
3000 // broadcasting an intent with NetworkInfo that's
3001 // suspended. This allows the applications an
3002 // opportunity to handle DISCONNECTED and SUSPENDED
3003 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08003004 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08003005 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08003006 handleConnect(info);
3007 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003008 if (mLockdownTracker != null) {
3009 mLockdownTracker.onNetworkInfoChanged(info);
3010 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003011 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003012 }
3013 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07003014 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05003015 // TODO: Temporary allowing network configuration
3016 // change not resetting sockets.
3017 // @see bug/4455071
3018 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003019 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003020 }
3021 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07003022 info = (NetworkInfo) msg.obj;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003023 int type = info.getType();
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07003024 updateNetworkSettings(mNetTrackers[type]);
3025 break;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003026 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003027 }
3028 }
3029 }
3030
3031 private class InternalHandler extends Handler {
3032 public InternalHandler(Looper looper) {
3033 super(looper);
3034 }
3035
3036 @Override
3037 public void handleMessage(Message msg) {
3038 NetworkInfo info;
3039 switch (msg.what) {
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003040 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003041 String causedBy = null;
3042 synchronized (ConnectivityService.this) {
3043 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3044 mNetTransitionWakeLock.isHeld()) {
3045 mNetTransitionWakeLock.release();
3046 causedBy = mNetTransitionWakeLockCausedBy;
3047 }
3048 }
3049 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003050 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003051 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07003052 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003053 }
3054 case EVENT_RESTORE_DEFAULT_NETWORK: {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003055 FeatureUser u = (FeatureUser)msg.obj;
3056 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003057 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003058 }
3059 case EVENT_INET_CONDITION_CHANGE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003060 int netType = msg.arg1;
3061 int condition = msg.arg2;
3062 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003063 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003064 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003065 case EVENT_INET_CONDITION_HOLD_END: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003066 int netType = msg.arg1;
3067 int sequence = msg.arg2;
Wink Saville151eaa62013-01-31 00:30:13 +00003068 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07003069 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003070 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003071 case EVENT_SET_NETWORK_PREFERENCE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003072 int preference = msg.arg1;
3073 handleSetNetworkPreference(preference);
3074 break;
3075 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003076 case EVENT_SET_MOBILE_DATA: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003077 boolean enabled = (msg.arg1 == ENABLED);
3078 handleSetMobileData(enabled);
3079 break;
3080 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003081 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003082 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07003083 break;
3084 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003085 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwalt34848c02011-03-25 13:09:25 -07003086 boolean met = (msg.arg1 == ENABLED);
3087 handleSetDependencyMet(msg.arg2, met);
3088 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003089 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003090 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville4f0de1e2011-08-04 15:01:58 -07003091 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07003092 sendStickyBroadcast(intent);
3093 break;
3094 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07003095 case EVENT_SET_POLICY_DATA_ENABLE: {
3096 final int networkType = msg.arg1;
3097 final boolean enabled = msg.arg2 == ENABLED;
3098 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003099 break;
3100 }
3101 case EVENT_VPN_STATE_CHANGED: {
3102 if (mLockdownTracker != null) {
3103 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3104 }
3105 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07003106 }
Wink Saville32506bc2013-06-29 21:10:57 -07003107 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3108 int tag = mEnableFailFastMobileDataTag.get();
3109 if (msg.arg1 == tag) {
3110 MobileDataStateTracker mobileDst =
3111 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3112 if (mobileDst != null) {
3113 mobileDst.setEnableFailFastMobileData(msg.arg2);
3114 }
3115 } else {
3116 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3117 + " != tag:" + tag);
3118 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003119 break;
Wink Saville32506bc2013-06-29 21:10:57 -07003120 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003121 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07003122 handleNetworkSamplingTimeout();
3123 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07003124 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003125 }
3126 }
3127 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003128
3129 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003130 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003131 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003132
3133 if (isTetheringSupported()) {
3134 return mTethering.tether(iface);
3135 } else {
3136 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3137 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003138 }
3139
3140 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003141 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003142 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003143
3144 if (isTetheringSupported()) {
3145 return mTethering.untether(iface);
3146 } else {
3147 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3148 }
3149 }
3150
3151 // javadoc from interface
3152 public int getLastTetherError(String iface) {
3153 enforceTetherAccessPermission();
3154
3155 if (isTetheringSupported()) {
3156 return mTethering.getLastTetherError(iface);
3157 } else {
3158 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3159 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003160 }
3161
3162 // TODO - proper iface API for selection by property, inspection, etc
3163 public String[] getTetherableUsbRegexs() {
3164 enforceTetherAccessPermission();
3165 if (isTetheringSupported()) {
3166 return mTethering.getTetherableUsbRegexs();
3167 } else {
3168 return new String[0];
3169 }
3170 }
3171
3172 public String[] getTetherableWifiRegexs() {
3173 enforceTetherAccessPermission();
3174 if (isTetheringSupported()) {
3175 return mTethering.getTetherableWifiRegexs();
3176 } else {
3177 return new String[0];
3178 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003179 }
3180
Danica Chang96567052010-08-11 14:54:43 -07003181 public String[] getTetherableBluetoothRegexs() {
3182 enforceTetherAccessPermission();
3183 if (isTetheringSupported()) {
3184 return mTethering.getTetherableBluetoothRegexs();
3185 } else {
3186 return new String[0];
3187 }
3188 }
3189
Mike Lockwooded4a1742011-07-19 13:04:47 -07003190 public int setUsbTethering(boolean enable) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08003191 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07003192 if (isTetheringSupported()) {
3193 return mTethering.setUsbTethering(enable);
3194 } else {
3195 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3196 }
3197 }
3198
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003199 // TODO - move iface listing, queries, etc to new module
3200 // javadoc from interface
3201 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003202 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003203 return mTethering.getTetherableIfaces();
3204 }
3205
3206 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003207 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003208 return mTethering.getTetheredIfaces();
3209 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003210
Jeff Sharkey300f08f2011-09-16 01:52:49 -07003211 @Override
3212 public String[] getTetheredIfacePairs() {
3213 enforceTetherAccessPermission();
3214 return mTethering.getTetheredIfacePairs();
3215 }
3216
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003217 public String[] getTetheringErroredIfaces() {
3218 enforceTetherAccessPermission();
3219 return mTethering.getErroredIfaces();
3220 }
3221
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003222 // if ro.tether.denied = true we default to no tethering
3223 // gservices could set the secure setting to 1 though to enable it on a build where it
3224 // had previously been turned off.
3225 public boolean isTetheringSupported() {
3226 enforceTetherAccessPermission();
3227 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownc67cf562012-09-25 15:03:20 -07003228 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3229 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt368095f2013-07-18 14:24:42 -07003230 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3231 mTethering.getTetherableWifiRegexs().length != 0 ||
3232 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3233 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003234 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003235
3236 // An API NetworkStateTrackers can call when they lose their network.
3237 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3238 // whichever happens first. The timer is started by the first caller and not
3239 // restarted by subsequent callers.
3240 public void requestNetworkTransitionWakelock(String forWhom) {
3241 enforceConnectivityInternalPermission();
3242 synchronized (this) {
3243 if (mNetTransitionWakeLock.isHeld()) return;
3244 mNetTransitionWakeLockSerialNumber++;
3245 mNetTransitionWakeLock.acquire();
3246 mNetTransitionWakeLockCausedBy = forWhom;
3247 }
3248 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003249 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003250 mNetTransitionWakeLockSerialNumber, 0),
3251 mNetTransitionWakeLockTimeout);
3252 return;
3253 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003254
Robert Greenwalt986c7412010-09-08 15:24:47 -07003255 // 100 percent is full good, 0 is full bad.
3256 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003257 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003258 mContext.enforceCallingOrSelfPermission(
3259 android.Manifest.permission.STATUS_BAR,
3260 "ConnectivityService");
3261
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003262 if (DBG) {
3263 int pid = getCallingPid();
3264 int uid = getCallingUid();
3265 String s = pid + "(" + uid + ") reports inet is " +
3266 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3267 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3268 mInetLog.add(s);
3269 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3270 mInetLog.remove(0);
3271 }
3272 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003273 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003274 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3275 }
3276
3277 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003278 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003279 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003280 return;
3281 }
3282 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003283 if (DBG) log("handleInetConditionChange: net=" + netType +
3284 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003285 return;
3286 }
Wink Savillea7d56572011-09-21 11:05:43 -07003287 if (VDBG) {
3288 log("handleInetConditionChange: net=" +
3289 netType + ", condition=" + condition +
Wink Saville151eaa62013-01-31 00:30:13 +00003290 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003291 }
Wink Saville151eaa62013-01-31 00:30:13 +00003292 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003293 int delay;
3294 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003295 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003296 // setup a new hold to debounce this
Wink Saville151eaa62013-01-31 00:30:13 +00003297 if (mDefaultInetCondition > 50) {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003298 delay = Settings.Global.getInt(mContext.getContentResolver(),
3299 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003300 } else {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003301 delay = Settings.Global.getInt(mContext.getContentResolver(),
3302 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003303 }
3304 mInetConditionChangeInFlight = true;
3305 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville151eaa62013-01-31 00:30:13 +00003306 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003307 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003308 // we've set the new condition, when this hold ends that will get picked up
3309 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003310 }
3311 }
3312
Wink Saville151eaa62013-01-31 00:30:13 +00003313 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003314 if (DBG) {
Wink Saville151eaa62013-01-31 00:30:13 +00003315 log("handleInetConditionHoldEnd: net=" + netType +
3316 ", condition=" + mDefaultInetCondition +
3317 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003318 }
3319 mInetConditionChangeInFlight = false;
3320
3321 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003322 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003323 return;
3324 }
3325 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003326 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003327 return;
3328 }
Wink Saville151eaa62013-01-31 00:30:13 +00003329 // TODO: Figure out why this optimization sometimes causes a
3330 // change in mDefaultInetCondition to be missed and the
3331 // UI to not be updated.
3332 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3333 // if (DBG) log("no change in condition - aborting");
3334 // return;
3335 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003336 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3337 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003338 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003339 return;
3340 }
Wink Saville151eaa62013-01-31 00:30:13 +00003341 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003342 sendInetConditionBroadcast(networkInfo);
3343 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003344 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003345
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003346 public ProxyProperties getProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003347 // this information is already available as a world read/writable jvm property
3348 // so this API change wouldn't have a benifit. It also breaks the passing
3349 // of proxy info to all the JVMs.
3350 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003351 synchronized (mProxyLock) {
Jason Monka5bf2842013-07-03 17:04:33 -04003352 ProxyProperties ret = mGlobalProxy;
3353 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3354 return ret;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003355 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003356 }
3357
3358 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003359 enforceConnectivityInternalPermission();
Jason Monka5bf2842013-07-03 17:04:33 -04003360
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003361 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003362 if (proxyProperties == mGlobalProxy) return;
3363 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3364 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3365
3366 String host = "";
3367 int port = 0;
3368 String exclList = "";
Jason Monka5bf2842013-07-03 17:04:33 -04003369 String pacFileUrl = "";
3370 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3371 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003372 mGlobalProxy = new ProxyProperties(proxyProperties);
3373 host = mGlobalProxy.getHost();
3374 port = mGlobalProxy.getPort();
3375 exclList = mGlobalProxy.getExclusionList();
Jason Monka5bf2842013-07-03 17:04:33 -04003376 if (proxyProperties.getPacFileUrl() != null) {
3377 pacFileUrl = proxyProperties.getPacFileUrl();
3378 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003379 } else {
3380 mGlobalProxy = null;
3381 }
3382 ContentResolver res = mContext.getContentResolver();
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003383 final long token = Binder.clearCallingIdentity();
3384 try {
3385 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3386 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3387 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3388 exclList);
Jason Monka5bf2842013-07-03 17:04:33 -04003389 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003390 } finally {
3391 Binder.restoreCallingIdentity(token);
3392 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003393 }
3394
3395 if (mGlobalProxy == null) {
3396 proxyProperties = mDefaultProxy;
3397 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003398 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003399 }
3400
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003401 private void loadGlobalProxy() {
3402 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003403 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3404 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3405 String exclList = Settings.Global.getString(res,
3406 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monka5bf2842013-07-03 17:04:33 -04003407 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3408 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3409 ProxyProperties proxyProperties;
3410 if (!TextUtils.isEmpty(pacFileUrl)) {
3411 proxyProperties = new ProxyProperties(pacFileUrl);
3412 } else {
3413 proxyProperties = new ProxyProperties(host, port, exclList);
3414 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003415 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003416 mGlobalProxy = proxyProperties;
3417 }
3418 }
3419 }
3420
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003421 public ProxyProperties getGlobalProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003422 // this information is already available as a world read/writable jvm property
3423 // so this API change wouldn't have a benifit. It also breaks the passing
3424 // of proxy info to all the JVMs.
3425 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003426 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003427 return mGlobalProxy;
3428 }
3429 }
3430
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003431 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04003432 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3433 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003434 proxy = null;
3435 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003436 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003437 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003438 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003439 mDefaultProxy = proxy;
3440
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003441 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003442 if (!mDefaultProxyDisabled) {
3443 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003444 }
3445 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003446 }
3447
3448 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003449 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3450 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003451 if (!TextUtils.isEmpty(proxy)) {
3452 String data[] = proxy.split(":");
Andreas Huber23bff232013-05-28 15:17:37 -07003453 if (data.length == 0) {
3454 return;
3455 }
3456
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003457 String proxyHost = data[0];
3458 int proxyPort = 8080;
3459 if (data.length > 1) {
3460 try {
3461 proxyPort = Integer.parseInt(data[1]);
3462 } catch (NumberFormatException e) {
3463 return;
3464 }
3465 }
3466 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3467 setGlobalProxy(p);
3468 }
3469 }
3470
3471 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003472 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monk0a9cc502013-08-23 19:21:25 -04003473 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt78f28112011-08-02 17:18:41 -07003474 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003475 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003476 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3477 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003478 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003479 final long ident = Binder.clearCallingIdentity();
3480 try {
3481 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3482 } finally {
3483 Binder.restoreCallingIdentity(ident);
3484 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003485 }
3486
3487 private static class SettingsObserver extends ContentObserver {
3488 private int mWhat;
3489 private Handler mHandler;
3490 SettingsObserver(Handler handler, int what) {
3491 super(handler);
3492 mHandler = handler;
3493 mWhat = what;
3494 }
3495
3496 void observe(Context context) {
3497 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003498 resolver.registerContentObserver(Settings.Global.getUriFor(
3499 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003500 }
3501
3502 @Override
3503 public void onChange(boolean selfChange) {
3504 mHandler.obtainMessage(mWhat).sendToTarget();
3505 }
3506 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003507
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003508 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003509 Slog.d(TAG, s);
3510 }
3511
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003512 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003513 Slog.e(TAG, s);
3514 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003515
repo syncf5de5572011-07-29 23:55:49 -07003516 int convertFeatureToNetworkType(int networkType, String feature) {
3517 int usedNetworkType = networkType;
3518
3519 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3520 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3521 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3522 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3523 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3524 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3525 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3526 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3527 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3528 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3529 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3530 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3531 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3532 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3533 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3534 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3535 } else {
3536 Slog.e(TAG, "Can't match any mobile netTracker!");
3537 }
3538 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3539 if (TextUtils.equals(feature, "p2p")) {
3540 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3541 } else {
3542 Slog.e(TAG, "Can't match any wifi netTracker!");
3543 }
3544 } else {
3545 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003546 }
repo syncf5de5572011-07-29 23:55:49 -07003547 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003548 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003549
3550 private static <T> T checkNotNull(T value, String message) {
3551 if (value == null) {
3552 throw new NullPointerException(message);
3553 }
3554 return value;
3555 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003556
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003557 /**
3558 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003559 * VpnBuilder and not available in ConnectivityManager. Permissions
3560 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003561 * @hide
3562 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003563 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003564 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003565 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003566 try {
3567 int type = mActiveDefaultNetwork;
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003568 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt15a41532012-08-21 19:27:00 -07003569 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003570 synchronized(mVpns) {
3571 mVpns.get(user).protect(socket,
3572 mNetTrackers[type].getLinkProperties().getInterfaceName());
3573 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003574 return true;
3575 }
3576 } catch (Exception e) {
3577 // ignore
3578 } finally {
3579 try {
3580 socket.close();
3581 } catch (Exception e) {
3582 // ignore
3583 }
3584 }
3585 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003586 }
3587
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003588 /**
3589 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003590 * and not available in ConnectivityManager. Permissions are checked
3591 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003592 * @hide
3593 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003594 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003595 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003596 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003597 int user = UserHandle.getUserId(Binder.getCallingUid());
3598 synchronized(mVpns) {
3599 return mVpns.get(user).prepare(oldPackage, newPackage);
3600 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003601 }
3602
Chad Brubaker11f22252013-07-11 13:29:30 -07003603 @Override
3604 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3605 enforceMarkNetworkSocketPermission();
3606 final long token = Binder.clearCallingIdentity();
3607 try {
3608 int mark = mNetd.getMarkForUid(uid);
3609 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3610 if (mark == -1) {
3611 mark = 0;
3612 }
3613 NetworkUtils.markSocket(socket.getFd(), mark);
3614 } catch (RemoteException e) {
3615 } finally {
3616 Binder.restoreCallingIdentity(token);
3617 }
3618 }
3619
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003620 /**
3621 * Configure a TUN interface and return its file descriptor. Parameters
3622 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003623 * and not available in ConnectivityManager. Permissions are checked in
3624 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003625 * @hide
3626 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003627 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003628 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003629 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003630 int user = UserHandle.getUserId(Binder.getCallingUid());
3631 synchronized(mVpns) {
3632 return mVpns.get(user).establish(config);
3633 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003634 }
3635
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003636 /**
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003637 * Start legacy VPN, controlling native daemons as needed. Creates a
3638 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003639 */
3640 @Override
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003641 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003642 throwIfLockdownEnabled();
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003643 final LinkProperties egress = getActiveLinkProperties();
3644 if (egress == null) {
3645 throw new IllegalStateException("Missing active network connection");
3646 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003647 int user = UserHandle.getUserId(Binder.getCallingUid());
3648 synchronized(mVpns) {
3649 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3650 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003651 }
3652
3653 /**
3654 * Return the information of the ongoing legacy VPN. This method is used
3655 * by VpnSettings and not available in ConnectivityManager. Permissions
3656 * are checked in Vpn class.
3657 * @hide
3658 */
3659 @Override
3660 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003661 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003662 int user = UserHandle.getUserId(Binder.getCallingUid());
3663 synchronized(mVpns) {
3664 return mVpns.get(user).getLegacyVpnInfo();
3665 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003666 }
3667
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003668 /**
Chad Brubaker94f3c8c2013-07-16 18:59:12 -07003669 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3670 * not available in ConnectivityManager.
3671 * Permissions are checked in Vpn class.
3672 * @hide
3673 */
3674 @Override
3675 public VpnConfig getVpnConfig() {
3676 int user = UserHandle.getUserId(Binder.getCallingUid());
3677 synchronized(mVpns) {
3678 return mVpns.get(user).getVpnConfig();
3679 }
3680 }
3681
3682 /**
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003683 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3684 * through NetworkStateTracker since it works differently. For example, it
3685 * needs to override DNS servers but never takes the default routes. It
3686 * relies on another data network, and it could keep existing connections
3687 * alive after reconnecting, switching between networks, or even resuming
3688 * from deep sleep. Calls from applications should be done synchronously
3689 * to avoid race conditions. As these are all hidden APIs, refactoring can
3690 * be done whenever a better abstraction is developed.
3691 */
3692 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003693 private VpnCallback() {
3694 }
3695
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003696 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003697 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003698 }
3699
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003700 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07003701 if (dnsServers == null) {
3702 restore();
3703 return;
3704 }
3705
3706 // Convert DNS servers into addresses.
3707 List<InetAddress> addresses = new ArrayList<InetAddress>();
3708 for (String address : dnsServers) {
3709 // Double check the addresses and remove invalid ones.
3710 try {
3711 addresses.add(InetAddress.parseNumericAddress(address));
3712 } catch (Exception e) {
3713 // ignore
3714 }
3715 }
3716 if (addresses.isEmpty()) {
3717 restore();
3718 return;
3719 }
3720
3721 // Concatenate search domains into a string.
3722 StringBuilder buffer = new StringBuilder();
3723 if (searchDomains != null) {
3724 for (String domain : searchDomains) {
3725 buffer.append(domain).append(' ');
3726 }
3727 }
3728 String domains = buffer.toString().trim();
3729
3730 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003731 synchronized (mDnsLock) {
Chad Brubaker73652d02013-07-23 17:13:36 -07003732 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003733 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003734
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003735 // Temporarily disable the default proxy (not global).
3736 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003737 mDefaultProxyDisabled = true;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003738 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003739 sendProxyBroadcast(null);
3740 }
3741 }
3742
3743 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003744 }
3745
Chia-chi Yehcc844502011-07-14 18:01:57 -07003746 public void restore() {
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003747 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003748 mDefaultProxyDisabled = false;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003749 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003750 sendProxyBroadcast(mDefaultProxy);
3751 }
3752 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003753 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003754
3755 public void protect(ParcelFileDescriptor socket) {
3756 try {
3757 final int mark = mNetd.getMarkForProtect();
3758 NetworkUtils.markSocket(socket.getFd(), mark);
3759 } catch (RemoteException e) {
3760 }
3761 }
3762
3763 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3764 for (RouteInfo route : routes) {
3765 try {
3766 mNetd.setMarkedForwardingRoute(interfaze, route);
3767 } catch (RemoteException e) {
3768 }
3769 }
3770 }
3771
3772 public void setMarkedForwarding(String interfaze) {
3773 try {
3774 mNetd.setMarkedForwarding(interfaze);
3775 } catch (RemoteException e) {
3776 }
3777 }
3778
3779 public void clearMarkedForwarding(String interfaze) {
3780 try {
3781 mNetd.clearMarkedForwarding(interfaze);
3782 } catch (RemoteException e) {
3783 }
3784 }
3785
3786 public void addUserForwarding(String interfaze, int uid) {
3787 int uidStart = uid * UserHandle.PER_USER_RANGE;
3788 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3789 addUidForwarding(interfaze, uidStart, uidEnd);
3790 }
3791
3792 public void clearUserForwarding(String interfaze, int uid) {
3793 int uidStart = uid * UserHandle.PER_USER_RANGE;
3794 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3795 clearUidForwarding(interfaze, uidStart, uidEnd);
3796 }
3797
3798 public void addUidForwarding(String interfaze, int uidStart, int uidEnd) {
3799 try {
3800 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
3801 mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
3802 } catch (RemoteException e) {
3803 }
3804
3805 }
3806
3807 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd) {
3808 try {
3809 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
3810 mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
3811 } catch (RemoteException e) {
3812 }
3813
3814 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003815 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003816
3817 @Override
3818 public boolean updateLockdownVpn() {
Jeff Sharkey760c6202013-01-31 17:22:26 -08003819 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3820 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3821 return false;
3822 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003823
3824 // Tear down existing lockdown if profile was removed
3825 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3826 if (mLockdownEnabled) {
Kenny Root0ded63c2013-02-14 10:18:38 -08003827 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003828 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3829 return false;
3830 }
3831
3832 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3833 final VpnProfile profile = VpnProfile.decode(
3834 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003835 int user = UserHandle.getUserId(Binder.getCallingUid());
3836 synchronized(mVpns) {
3837 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3838 profile));
3839 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003840 } else {
3841 setLockdownTracker(null);
3842 }
3843
3844 return true;
3845 }
3846
3847 /**
3848 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3849 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3850 */
3851 private void setLockdownTracker(LockdownVpnTracker tracker) {
3852 // Shutdown any existing tracker
3853 final LockdownVpnTracker existing = mLockdownTracker;
3854 mLockdownTracker = null;
3855 if (existing != null) {
3856 existing.shutdown();
3857 }
3858
3859 try {
3860 if (tracker != null) {
3861 mNetd.setFirewallEnabled(true);
Jeff Sharkeydb44d2c2013-02-28 16:57:58 -08003862 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003863 mLockdownTracker = tracker;
3864 mLockdownTracker.init();
3865 } else {
3866 mNetd.setFirewallEnabled(false);
3867 }
3868 } catch (RemoteException e) {
3869 // ignored; NMS lives inside system_server
3870 }
3871 }
3872
3873 private void throwIfLockdownEnabled() {
3874 if (mLockdownEnabled) {
3875 throw new IllegalStateException("Unavailable in lockdown mode");
3876 }
3877 }
Robert Greenwalt15a41532012-08-21 19:27:00 -07003878
3879 public void supplyMessenger(int networkType, Messenger messenger) {
3880 enforceConnectivityInternalPermission();
3881
3882 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3883 mNetTrackers[networkType].supplyMessenger(messenger);
3884 }
3885 }
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -07003886
3887 public int findConnectionTypeForIface(String iface) {
3888 enforceConnectivityInternalPermission();
3889
3890 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3891 for (NetworkStateTracker tracker : mNetTrackers) {
3892 if (tracker != null) {
3893 LinkProperties lp = tracker.getLinkProperties();
3894 if (lp != null && iface.equals(lp.getInterfaceName())) {
3895 return tracker.getNetworkInfo().getType();
3896 }
3897 }
3898 }
3899 return ConnectivityManager.TYPE_NONE;
3900 }
Wink Saville32506bc2013-06-29 21:10:57 -07003901
3902 /**
3903 * Have mobile data fail fast if enabled.
3904 *
3905 * @param enabled DctConstants.ENABLED/DISABLED
3906 */
3907 private void setEnableFailFastMobileData(int enabled) {
3908 int tag;
3909
3910 if (enabled == DctConstants.ENABLED) {
3911 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3912 } else {
3913 tag = mEnableFailFastMobileDataTag.get();
3914 }
3915 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3916 enabled));
3917 }
3918
Wink Savilled23fa092013-08-16 17:17:28 -07003919 private boolean isMobileDataStateTrackerReady() {
3920 MobileDataStateTracker mdst =
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003921 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savilled23fa092013-08-16 17:17:28 -07003922 return (mdst != null) && (mdst.isReady());
3923 }
3924
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003925 /**
3926 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3927 */
3928
3929 /**
3930 * No connection was possible to the network.
Wink Saville9685cd12013-09-06 09:53:08 -07003931 * This is NOT a warm sim.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003932 */
Wink Saville9685cd12013-09-06 09:53:08 -07003933 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003934
3935 /**
3936 * A connection was made to the internet, all is well.
Wink Saville9685cd12013-09-06 09:53:08 -07003937 * This is NOT a warm sim.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003938 */
Wink Saville9685cd12013-09-06 09:53:08 -07003939 private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003940
3941 /**
3942 * A connection was made but no dns server was available to resolve a name to address.
Wink Saville9685cd12013-09-06 09:53:08 -07003943 * This is NOT a warm sim since provisioning network is supported.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003944 */
Wink Saville9685cd12013-09-06 09:53:08 -07003945 private static final int CMP_RESULT_CODE_NO_DNS = 2;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003946
3947 /**
3948 * A connection was made but could not open a TCP connection.
Wink Saville9685cd12013-09-06 09:53:08 -07003949 * This is NOT a warm sim since provisioning network is supported.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003950 */
Wink Saville9685cd12013-09-06 09:53:08 -07003951 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
3952
3953 /**
3954 * A connection was made but there was a redirection, we appear to be in walled garden.
3955 * This is an indication of a warm sim on a mobile network such as T-Mobile.
3956 */
3957 private static final int CMP_RESULT_CODE_REDIRECTED = 4;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003958
3959 /**
3960 * The mobile network is a provisioning network.
Wink Saville9685cd12013-09-06 09:53:08 -07003961 * This is an indication of a warm sim on a mobile network such as AT&T.
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003962 */
Wink Saville9685cd12013-09-06 09:53:08 -07003963 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003964
Wink Saville9685cd12013-09-06 09:53:08 -07003965 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003966
Wink Saville32506bc2013-06-29 21:10:57 -07003967 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003968 public int checkMobileProvisioning(int suggestedTimeOutMs) {
3969 int timeOutMs = -1;
3970 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
3971 enforceConnectivityInternalPermission();
Wink Savilled469c472013-07-02 10:55:14 -07003972
Wink Saville32506bc2013-06-29 21:10:57 -07003973 final long token = Binder.clearCallingIdentity();
3974 try {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003975 timeOutMs = suggestedTimeOutMs;
3976 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3977 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3978 }
3979
3980 // Check that mobile networks are supported
3981 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3982 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3983 if (DBG) log("checkMobileProvisioning: X no mobile network");
3984 return timeOutMs;
3985 }
3986
3987 // If we're already checking don't do it again
3988 // TODO: Add a queue of results...
3989 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
3990 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
3991 return timeOutMs;
3992 }
3993
3994 // Start off with notification off
3995 setProvNotificationVisible(false, ConnectivityManager.TYPE_NONE, null, null);
3996
3997 // See if we've alreadying determined if we've got a provsioning connection
3998 // if so we don't need to do anything active
3999 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4000 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4001 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4002
4003 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4004 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4005 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4006
4007 if (isDefaultProvisioning || isHipriProvisioning) {
4008 if (mIsNotificationVisible) {
4009 if (DBG) {
4010 log("checkMobileProvisioning: provisioning-ignore notification is visible");
4011 }
4012 } else {
4013 NetworkInfo ni = null;
4014 if (isDefaultProvisioning) {
4015 ni = mdstDefault.getNetworkInfo();
4016 }
4017 if (isHipriProvisioning) {
4018 ni = mdstHipri.getNetworkInfo();
4019 }
4020 String url = getMobileProvisioningUrl();
4021 if ((ni != null) && (!TextUtils.isEmpty(url))) {
4022 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(), url);
4023 } else {
4024 if (DBG) log("checkMobileProvisioning: provisioning but no url, ignore");
4025 }
4026 }
4027 mIsCheckingMobileProvisioning.set(false);
4028 return timeOutMs;
4029 }
4030
Wink Saville32506bc2013-06-29 21:10:57 -07004031 CheckMp checkMp = new CheckMp(mContext, this);
4032 CheckMp.CallBack cb = new CheckMp.CallBack() {
4033 @Override
4034 void onComplete(Integer result) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004035 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Saville32506bc2013-06-29 21:10:57 -07004036 NetworkInfo ni =
4037 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4038 switch(result) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004039 case CMP_RESULT_CODE_CONNECTABLE:
Wink Saville9685cd12013-09-06 09:53:08 -07004040 case CMP_RESULT_CODE_NO_CONNECTION:
4041 case CMP_RESULT_CODE_NO_DNS:
4042 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004043 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Saville32506bc2013-06-29 21:10:57 -07004044 break;
4045 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004046 case CMP_RESULT_CODE_REDIRECTED: {
4047 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalt39d56012013-07-16 12:06:09 -07004048 String url = getMobileProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004049 if (TextUtils.isEmpty(url)) {
Robert Greenwalt39d56012013-07-16 12:06:09 -07004050 url = getMobileRedirectedProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004051 }
4052 if (TextUtils.isEmpty(url) == false) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004053 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
4054 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(),
4055 url);
Wink Saville32506bc2013-06-29 21:10:57 -07004056 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004057 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Saville32506bc2013-06-29 21:10:57 -07004058 }
4059 break;
4060 }
Wink Saville9685cd12013-09-06 09:53:08 -07004061 case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
Robert Greenwalt39d56012013-07-16 12:06:09 -07004062 String url = getMobileProvisioningUrl();
Wink Saville32506bc2013-06-29 21:10:57 -07004063 if (TextUtils.isEmpty(url) == false) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004064 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
4065 setProvNotificationVisible(true, ni.getType(), ni.getExtraInfo(),
4066 url);
Wink Saville32506bc2013-06-29 21:10:57 -07004067 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004068 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Saville32506bc2013-06-29 21:10:57 -07004069 }
4070 break;
4071 }
4072 default: {
4073 loge("CheckMp.onComplete: ignore unexpected result=" + result);
4074 break;
4075 }
4076 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004077 mIsCheckingMobileProvisioning.set(false);
Wink Saville32506bc2013-06-29 21:10:57 -07004078 }
4079 };
4080 CheckMp.Params params =
4081 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004082 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Saville32506bc2013-06-29 21:10:57 -07004083 checkMp.execute(params);
4084 } finally {
4085 Binder.restoreCallingIdentity(token);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004086 if (DBG) log("checkMobileProvisioning: X");
Wink Saville32506bc2013-06-29 21:10:57 -07004087 }
4088 return timeOutMs;
4089 }
4090
4091 static class CheckMp extends
4092 AsyncTask<CheckMp.Params, Void, Integer> {
4093 private static final String CHECKMP_TAG = "CheckMp";
4094 public static final int MAX_TIMEOUT_MS = 60000;
4095 private static final int SOCKET_TIMEOUT_MS = 5000;
4096 private Context mContext;
4097 private ConnectivityService mCs;
4098 private TelephonyManager mTm;
4099 private Params mParams;
4100
4101 /**
4102 * Parameters for AsyncTask.execute
4103 */
4104 static class Params {
4105 private String mUrl;
4106 private long mTimeOutMs;
4107 private CallBack mCb;
4108
4109 Params(String url, long timeOutMs, CallBack cb) {
4110 mUrl = url;
4111 mTimeOutMs = timeOutMs;
4112 mCb = cb;
4113 }
4114
4115 @Override
4116 public String toString() {
4117 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4118 }
4119 }
4120
4121 /**
4122 * The call back object passed in Params. onComplete will be called
4123 * on the main thread.
4124 */
4125 abstract static class CallBack {
4126 // Called on the main thread.
4127 abstract void onComplete(Integer result);
4128 }
4129
4130 public CheckMp(Context context, ConnectivityService cs) {
4131 mContext = context;
4132 mCs = cs;
4133
4134 // Setup access to TelephonyService we'll be using.
4135 mTm = (TelephonyManager) mContext.getSystemService(
4136 Context.TELEPHONY_SERVICE);
4137 }
4138
4139 /**
4140 * Get the default url to use for the test.
4141 */
4142 public String getDefaultUrl() {
4143 // See http://go/clientsdns for usage approval
4144 String server = Settings.Global.getString(mContext.getContentResolver(),
4145 Settings.Global.CAPTIVE_PORTAL_SERVER);
4146 if (server == null) {
4147 server = "clients3.google.com";
4148 }
4149 return "http://" + server + "/generate_204";
4150 }
4151
4152 /**
4153 * Detect if its possible to connect to the http url. DNS based detection techniques
4154 * do not work at all hotspots. The best way to check is to perform a request to
4155 * a known address that fetches the data we expect.
4156 */
4157 private synchronized Integer isMobileOk(Params params) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004158 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004159 Uri orgUri = Uri.parse(params.mUrl);
4160 Random rand = new Random();
4161 mParams = params;
4162
Wink Saville69e2de02013-08-13 12:41:06 -07004163 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
4164 log("isMobileOk: not mobile capable");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004165 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville69e2de02013-08-13 12:41:06 -07004166 return result;
4167 }
Wink Saville32506bc2013-06-29 21:10:57 -07004168
Wink Saville69e2de02013-08-13 12:41:06 -07004169 try {
Wink Saville32506bc2013-06-29 21:10:57 -07004170 // Continue trying to connect until time has run out
4171 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville15f12922013-08-07 11:02:57 -07004172
Wink Savilled23fa092013-08-16 17:17:28 -07004173 if (!mCs.isMobileDataStateTrackerReady()) {
4174 // Wait for MobileDataStateTracker to be ready.
4175 if (DBG) log("isMobileOk: mdst is not ready");
4176 while(SystemClock.elapsedRealtime() < endTime) {
4177 if (mCs.isMobileDataStateTrackerReady()) {
4178 // Enable fail fast as we'll do retries here and use a
4179 // hipri connection so the default connection stays active.
4180 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4181 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4182 break;
4183 }
4184 sleep(1);
4185 }
4186 }
4187
4188 log("isMobileOk: start hipri url=" + params.mUrl);
4189
Wink Saville15f12922013-08-07 11:02:57 -07004190 // First wait until we can start using hipri
4191 Binder binder = new Binder();
4192 while(SystemClock.elapsedRealtime() < endTime) {
4193 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4194 Phone.FEATURE_ENABLE_HIPRI, binder);
4195 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4196 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4197 log("isMobileOk: hipri started");
4198 break;
4199 }
4200 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004201 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville15f12922013-08-07 11:02:57 -07004202 sleep(1);
4203 }
4204
4205 // Continue trying to connect until time has run out
Wink Saville32506bc2013-06-29 21:10:57 -07004206 while(SystemClock.elapsedRealtime() < endTime) {
4207 try {
4208 // Wait for hipri to connect.
4209 // TODO: Don't poll and handle situation where hipri fails
4210 // because default is retrying. See b/9569540
4211 NetworkInfo.State state = mCs
4212 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4213 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004214 if (true/*VDBG*/) {
Wink Savilled28eef42013-07-31 15:49:04 -07004215 log("isMobileOk: not connected ni=" +
Wink Saville32506bc2013-06-29 21:10:57 -07004216 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Savilled28eef42013-07-31 15:49:04 -07004217 }
Wink Saville32506bc2013-06-29 21:10:57 -07004218 sleep(1);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004219 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004220 continue;
4221 }
4222
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004223 // Hipri has started check if this is a provisioning url
4224 MobileDataStateTracker mdst = (MobileDataStateTracker)
4225 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4226 if (mdst.isProvisioningNetwork()) {
Wink Saville9685cd12013-09-06 09:53:08 -07004227 if (DBG) log("isMobileOk: isProvisioningNetwork is true");
4228 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004229 return result;
4230 } else {
4231 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4232 }
4233
Wink Saville32506bc2013-06-29 21:10:57 -07004234 // Get of the addresses associated with the url host. We need to use the
4235 // address otherwise HttpURLConnection object will use the name to get
4236 // the addresses and is will try every address but that will bypass the
4237 // route to host we setup and the connection could succeed as the default
4238 // interface might be connected to the internet via wifi or other interface.
4239 InetAddress[] addresses;
4240 try {
4241 addresses = InetAddress.getAllByName(orgUri.getHost());
4242 } catch (UnknownHostException e) {
4243 log("isMobileOk: UnknownHostException");
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004244 result = CMP_RESULT_CODE_NO_DNS;
Wink Saville32506bc2013-06-29 21:10:57 -07004245 return result;
4246 }
4247 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4248
4249 // Get the type of addresses supported by this link
4250 LinkProperties lp = mCs.getLinkProperties(
4251 ConnectivityManager.TYPE_MOBILE_HIPRI);
Lorenzo Colitti09de4182013-08-08 11:00:12 +09004252 boolean linkHasIpv4 = lp.hasIPv4Address();
4253 boolean linkHasIpv6 = lp.hasIPv6Address();
Wink Saville32506bc2013-06-29 21:10:57 -07004254 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4255 + " linkHasIpv6=" + linkHasIpv6);
4256
4257 // Loop through at most 3 valid addresses or all of the address or until
4258 // we run out of time
4259 int loops = Math.min(3, addresses.length);
4260 for(int validAddr=0, addrTried=0;
4261 (validAddr < loops) && (addrTried < addresses.length)
4262 && (SystemClock.elapsedRealtime() < endTime);
4263 addrTried ++) {
4264
4265 // Choose the address at random but make sure its type is supported
4266 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
4267 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
4268 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
4269 // Valid address, so use it
4270 validAddr += 1;
4271 } else {
4272 // Invalid address so try next address
4273 continue;
4274 }
4275
4276 // Make a route to host so we check the specific interface.
4277 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4278 hostAddr.getAddress())) {
4279 // Wait a short time to be sure the route is established ??
4280 log("isMobileOk:"
4281 + " wait to establish route to hostAddr=" + hostAddr);
4282 sleep(3);
4283 } else {
4284 log("isMobileOk:"
4285 + " could not establish route to hostAddr=" + hostAddr);
4286 continue;
4287 }
4288
4289 // Rewrite the url to have numeric address to use the specific route.
4290 // I also set the "Connection" to "Close" as by default "Keep-Alive"
4291 // is used which is useless in this case.
4292 URL newUrl = new URL(orgUri.getScheme() + "://"
4293 + hostAddr.getHostAddress() + orgUri.getPath());
4294 log("isMobileOk: newUrl=" + newUrl);
4295
4296 HttpURLConnection urlConn = null;
4297 try {
4298 // Open the connection set the request header and get the response
4299 urlConn = (HttpURLConnection) newUrl.openConnection(
4300 java.net.Proxy.NO_PROXY);
4301 urlConn.setInstanceFollowRedirects(false);
4302 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4303 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4304 urlConn.setUseCaches(false);
4305 urlConn.setAllowUserInteraction(false);
4306 urlConn.setRequestProperty("Connection", "close");
4307 int responseCode = urlConn.getResponseCode();
Wink Saville9685cd12013-09-06 09:53:08 -07004308
4309 // For debug display the headers
4310 Map<String, List<String>> headers = urlConn.getHeaderFields();
4311 log("isMobileOk: headers=" + headers);
4312
4313 // Close the connection
Wink Saville32506bc2013-06-29 21:10:57 -07004314 urlConn.disconnect();
4315 urlConn = null;
Wink Saville9685cd12013-09-06 09:53:08 -07004316
4317 if (responseCode == 204) {
4318 // Return
4319 log("isMobileOk: expected responseCode=" + responseCode);
4320 result = CMP_RESULT_CODE_CONNECTABLE;
4321 return result;
4322 } else {
4323 // Retry to be sure this was redirected, we've gotten
4324 // occasions where a server returned 200 even though
4325 // the device didn't have a "warm" sim.
4326 log("isMobileOk: not expected responseCode=" + responseCode);
4327 result = CMP_RESULT_CODE_REDIRECTED;
4328 }
Wink Saville32506bc2013-06-29 21:10:57 -07004329 } catch (Exception e) {
4330 log("isMobileOk: HttpURLConnection Exception e=" + e);
Wink Saville9685cd12013-09-06 09:53:08 -07004331 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Saville32506bc2013-06-29 21:10:57 -07004332 if (urlConn != null) {
4333 urlConn.disconnect();
4334 urlConn = null;
4335 }
4336 }
4337 }
Wink Saville9685cd12013-09-06 09:53:08 -07004338 log("isMobileOk: loops|timed out result=" + result);
Wink Saville32506bc2013-06-29 21:10:57 -07004339 return result;
4340 } catch (Exception e) {
4341 log("isMobileOk: Exception e=" + e);
4342 continue;
4343 }
4344 }
4345 log("isMobileOk: timed out");
4346 } finally {
4347 log("isMobileOk: F stop hipri");
4348 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4349 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4350 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004351
4352 // Wait for hipri to disconnect.
4353 long endTime = SystemClock.elapsedRealtime() + 5000;
4354
4355 while(SystemClock.elapsedRealtime() < endTime) {
4356 NetworkInfo.State state = mCs
4357 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4358 if (state != NetworkInfo.State.DISCONNECTED) {
4359 if (VDBG) {
4360 log("isMobileOk: connected ni=" +
4361 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4362 }
4363 sleep(1);
4364 continue;
4365 }
4366 }
4367
Wink Saville32506bc2013-06-29 21:10:57 -07004368 log("isMobileOk: X result=" + result);
4369 }
4370 return result;
4371 }
4372
4373 @Override
4374 protected Integer doInBackground(Params... params) {
4375 return isMobileOk(params[0]);
4376 }
4377
4378 @Override
4379 protected void onPostExecute(Integer result) {
4380 log("onPostExecute: result=" + result);
4381 if ((mParams != null) && (mParams.mCb != null)) {
4382 mParams.mCb.onComplete(result);
4383 }
4384 }
4385
4386 private String inetAddressesToString(InetAddress[] addresses) {
4387 StringBuffer sb = new StringBuffer();
4388 boolean firstTime = true;
4389 for(InetAddress addr : addresses) {
4390 if (firstTime) {
4391 firstTime = false;
4392 } else {
4393 sb.append(",");
4394 }
4395 sb.append(addr);
4396 }
4397 return sb.toString();
4398 }
4399
4400 private void printNetworkInfo() {
4401 boolean hasIccCard = mTm.hasIccCard();
4402 int simState = mTm.getSimState();
4403 log("hasIccCard=" + hasIccCard
4404 + " simState=" + simState);
4405 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4406 if (ni != null) {
4407 log("ni.length=" + ni.length);
4408 for (NetworkInfo netInfo: ni) {
4409 log("netInfo=" + netInfo.toString());
4410 }
4411 } else {
4412 log("no network info ni=null");
4413 }
4414 }
4415
4416 /**
4417 * Sleep for a few seconds then return.
4418 * @param seconds
4419 */
4420 private static void sleep(int seconds) {
4421 try {
4422 Thread.sleep(seconds * 1000);
4423 } catch (InterruptedException e) {
4424 e.printStackTrace();
4425 }
4426 }
4427
Wink Saville32506bc2013-06-29 21:10:57 -07004428 private void log(String s) {
4429 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4430 }
4431 }
4432
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004433 // TODO: Move to ConnectivityManager and make public?
4434 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4435 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Saville32506bc2013-06-29 21:10:57 -07004436
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004437 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4438 @Override
4439 public void onReceive(Context context, Intent intent) {
4440 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4441 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4442 }
4443 }
4444 };
4445
4446 private void handleMobileProvisioningAction(String url) {
4447 // Notication mark notification as not visible
4448 setProvNotificationVisible(false, ConnectivityManager.TYPE_NONE, null, null);
4449
4450 // If provisioning network handle as a special case,
4451 // otherwise launch browser with the intent directly.
4452 NetworkInfo ni = getProvisioningNetworkInfo();
Wink Savilleb1a32022013-09-05 12:02:25 -07004453 if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004454 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4455 MobileDataStateTracker mdst = (MobileDataStateTracker)
4456 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4457 mdst.enableMobileProvisioning(url);
4458 } else {
4459 if (DBG) log("handleMobileProvisioningAction: on default network");
4460 Intent newIntent =
4461 new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4462 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4463 Intent.FLAG_ACTIVITY_NEW_TASK);
4464 try {
4465 mContext.startActivity(newIntent);
4466 } catch (ActivityNotFoundException e) {
4467 loge("handleMobileProvisioningAction: startActivity failed" + e);
4468 }
4469 }
4470 }
4471
4472 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4473 private volatile boolean mIsNotificationVisible = false;
4474
4475 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4476 String url) {
4477 if (DBG) {
4478 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4479 + " extraInfo=" + extraInfo + " url=" + url);
4480 }
Wink Saville32506bc2013-06-29 21:10:57 -07004481
4482 Resources r = Resources.getSystem();
4483 NotificationManager notificationManager = (NotificationManager) mContext
4484 .getSystemService(Context.NOTIFICATION_SERVICE);
4485
4486 if (visible) {
4487 CharSequence title;
4488 CharSequence details;
4489 int icon;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004490 Intent intent;
4491 Notification notification = new Notification();
4492 switch (networkType) {
Wink Saville32506bc2013-06-29 21:10:57 -07004493 case ConnectivityManager.TYPE_WIFI:
Wink Saville32506bc2013-06-29 21:10:57 -07004494 title = r.getString(R.string.wifi_available_sign_in, 0);
4495 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004496 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004497 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004498 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4499 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4500 Intent.FLAG_ACTIVITY_NEW_TASK);
4501 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004502 break;
4503 case ConnectivityManager.TYPE_MOBILE:
4504 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Saville32506bc2013-06-29 21:10:57 -07004505 title = r.getString(R.string.network_available_sign_in, 0);
4506 // TODO: Change this to pull from NetworkInfo once a printable
4507 // name has been added to it
4508 details = mTelephonyManager.getNetworkOperatorName();
4509 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004510 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4511 intent.putExtra("EXTRA_URL", url);
4512 intent.setFlags(0);
4513 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004514 break;
4515 default:
Wink Saville32506bc2013-06-29 21:10:57 -07004516 title = r.getString(R.string.network_available_sign_in, 0);
4517 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004518 extraInfo);
Wink Saville32506bc2013-06-29 21:10:57 -07004519 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004520 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4521 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4522 Intent.FLAG_ACTIVITY_NEW_TASK);
4523 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville32506bc2013-06-29 21:10:57 -07004524 break;
4525 }
4526
Wink Saville32506bc2013-06-29 21:10:57 -07004527 notification.when = 0;
4528 notification.icon = icon;
4529 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Saville32506bc2013-06-29 21:10:57 -07004530 notification.tickerText = title;
4531 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4532
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004533 try {
4534 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4535 } catch (NullPointerException npe) {
4536 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4537 npe.printStackTrace();
4538 }
Wink Saville32506bc2013-06-29 21:10:57 -07004539 } else {
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004540 try {
4541 notificationManager.cancel(NOTIFICATION_ID, 1);
4542 } catch (NullPointerException npe) {
4543 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4544 npe.printStackTrace();
4545 }
Wink Saville32506bc2013-06-29 21:10:57 -07004546 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004547 mIsNotificationVisible = visible;
Wink Saville32506bc2013-06-29 21:10:57 -07004548 }
4549
Robert Greenwalt39d56012013-07-16 12:06:09 -07004550 /** Location to an updatable file listing carrier provisioning urls.
4551 * An example:
4552 *
4553 * <?xml version="1.0" encoding="utf-8"?>
4554 * <provisioningUrls>
4555 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4556 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4557 * </provisioningUrls>
4558 */
4559 private static final String PROVISIONING_URL_PATH =
4560 "/data/misc/radio/provisioning_urls.xml";
4561 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville32506bc2013-06-29 21:10:57 -07004562
Robert Greenwalt39d56012013-07-16 12:06:09 -07004563 /** XML tag for root element. */
4564 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4565 /** XML tag for individual url */
4566 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4567 /** XML tag for redirected url */
4568 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4569 /** XML attribute for mcc */
4570 private static final String ATTR_MCC = "mcc";
4571 /** XML attribute for mnc */
4572 private static final String ATTR_MNC = "mnc";
4573
4574 private static final int REDIRECTED_PROVISIONING = 1;
4575 private static final int PROVISIONING = 2;
4576
4577 private String getProvisioningUrlBaseFromFile(int type) {
4578 FileReader fileReader = null;
4579 XmlPullParser parser = null;
4580 Configuration config = mContext.getResources().getConfiguration();
4581 String tagType;
4582
4583 switch (type) {
4584 case PROVISIONING:
4585 tagType = TAG_PROVISIONING_URL;
4586 break;
4587 case REDIRECTED_PROVISIONING:
4588 tagType = TAG_REDIRECTED_URL;
4589 break;
4590 default:
4591 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4592 type);
4593 }
4594
4595 try {
4596 fileReader = new FileReader(mProvisioningUrlFile);
4597 parser = Xml.newPullParser();
4598 parser.setInput(fileReader);
4599 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4600
4601 while (true) {
4602 XmlUtils.nextElement(parser);
4603
4604 String element = parser.getName();
4605 if (element == null) break;
4606
4607 if (element.equals(tagType)) {
4608 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4609 try {
4610 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4611 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4612 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4613 parser.next();
4614 if (parser.getEventType() == XmlPullParser.TEXT) {
4615 return parser.getText();
4616 }
4617 }
4618 }
4619 } catch (NumberFormatException e) {
4620 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4621 }
4622 }
4623 }
4624 return null;
4625 } catch (FileNotFoundException e) {
4626 loge("Carrier Provisioning Urls file not found");
4627 } catch (XmlPullParserException e) {
4628 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4629 } catch (IOException e) {
4630 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4631 } finally {
4632 if (fileReader != null) {
4633 try {
4634 fileReader.close();
4635 } catch (IOException e) {}
4636 }
4637 }
4638 return null;
4639 }
4640
Wink Saville8432cf42013-07-20 20:31:59 -07004641 @Override
4642 public String getMobileRedirectedProvisioningUrl() {
4643 enforceConnectivityInternalPermission();
Robert Greenwalt39d56012013-07-16 12:06:09 -07004644 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4645 if (TextUtils.isEmpty(url)) {
4646 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4647 }
4648 return url;
4649 }
4650
Wink Saville8432cf42013-07-20 20:31:59 -07004651 @Override
Robert Greenwalt39d56012013-07-16 12:06:09 -07004652 public String getMobileProvisioningUrl() {
4653 enforceConnectivityInternalPermission();
4654 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4655 if (TextUtils.isEmpty(url)) {
4656 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville8432cf42013-07-20 20:31:59 -07004657 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004658 } else {
Wink Saville8432cf42013-07-20 20:31:59 -07004659 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalt39d56012013-07-16 12:06:09 -07004660 }
Wink Savillec118d7e2013-07-10 23:00:07 -07004661 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville32506bc2013-06-29 21:10:57 -07004662 if (!TextUtils.isEmpty(url)) {
Wink Savillec118d7e2013-07-10 23:00:07 -07004663 String phoneNumber = mTelephonyManager.getLine1Number();
4664 if (TextUtils.isEmpty(phoneNumber)) {
4665 phoneNumber = "0000000000";
4666 }
Wink Saville32506bc2013-06-29 21:10:57 -07004667 url = String.format(url,
4668 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4669 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savillec118d7e2013-07-10 23:00:07 -07004670 phoneNumber /* Phone numer */);
Wink Saville32506bc2013-06-29 21:10:57 -07004671 }
4672
Wink Saville32506bc2013-06-29 21:10:57 -07004673 return url;
4674 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07004675
Wink Saville9a1a7ef2013-08-29 08:55:16 -07004676 @Override
4677 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4678 String extraInfo, String url) {
4679 enforceConnectivityInternalPermission();
4680 setProvNotificationVisible(visible, networkType, extraInfo, url);
4681 }
Wink Savillecb117d32013-08-29 14:57:08 -07004682
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07004683 @Override
4684 public void setAirplaneMode(boolean enable) {
4685 enforceConnectivityInternalPermission();
4686 final ContentResolver cr = mContext.getContentResolver();
4687 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
4688 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4689 intent.putExtra("state", enable);
4690 final long ident = Binder.clearCallingIdentity();
4691 try {
4692 mContext.sendBroadcast(intent);
4693 } finally {
4694 Binder.restoreCallingIdentity(ident);
4695 }
4696 }
4697
Chad Brubakerb7652cd2013-06-14 11:16:51 -07004698 private void onUserStart(int userId) {
4699 synchronized(mVpns) {
4700 Vpn userVpn = mVpns.get(userId);
4701 if (userVpn != null) {
4702 loge("Starting user already has a VPN");
4703 return;
4704 }
4705 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4706 mVpns.put(userId, userVpn);
4707 userVpn.startMonitoring(mContext, mTrackerHandler);
4708 }
4709 }
4710
4711 private void onUserStop(int userId) {
4712 synchronized(mVpns) {
4713 Vpn userVpn = mVpns.get(userId);
4714 if (userVpn == null) {
4715 loge("Stopping user has no VPN");
4716 return;
4717 }
4718 mVpns.delete(userId);
4719 }
4720 }
4721
4722 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4723 @Override
4724 public void onReceive(Context context, Intent intent) {
4725 final String action = intent.getAction();
4726 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4727 if (userId == UserHandle.USER_NULL) return;
4728
4729 if (Intent.ACTION_USER_STARTING.equals(action)) {
4730 onUserStart(userId);
4731 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4732 onUserStop(userId);
4733 }
4734 }
4735 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004736
4737 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004738 public LinkQualityInfo getLinkQualityInfo(int networkType) {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004739 enforceAccessPermission();
4740 if (isNetworkTypeValid(networkType)) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004741 return mNetTrackers[networkType].getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004742 } else {
4743 return null;
4744 }
4745 }
4746
4747 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004748 public LinkQualityInfo getActiveLinkQualityInfo() {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004749 enforceAccessPermission();
4750 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004751 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004752 } else {
4753 return null;
4754 }
4755 }
4756
4757 @Override
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004758 public LinkQualityInfo[] getAllLinkQualityInfo() {
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004759 enforceAccessPermission();
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004760 final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004761 for (NetworkStateTracker tracker : mNetTrackers) {
4762 if (tracker != null) {
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004763 LinkQualityInfo li = tracker.getLinkQualityInfo();
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004764 if (li != null) {
4765 result.add(li);
4766 }
4767 }
4768 }
4769
Vinit Deshapnde00d4b8a2013-09-04 14:11:24 -07004770 return result.toArray(new LinkQualityInfo[result.size()]);
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07004771 }
4772
4773 /* Infrastructure for network sampling */
4774
4775 private void handleNetworkSamplingTimeout() {
4776
4777 log("Sampling interval elapsed, updating statistics ..");
4778
4779 // initialize list of interfaces ..
4780 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4781 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4782 for (NetworkStateTracker tracker : mNetTrackers) {
4783 if (tracker != null) {
4784 String ifaceName = tracker.getNetworkInterfaceName();
4785 if (ifaceName != null) {
4786 mapIfaceToSample.put(ifaceName, null);
4787 }
4788 }
4789 }
4790
4791 // Read samples for all interfaces
4792 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4793
4794 // process samples for all networks
4795 for (NetworkStateTracker tracker : mNetTrackers) {
4796 if (tracker != null) {
4797 String ifaceName = tracker.getNetworkInterfaceName();
4798 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4799 if (ss != null) {
4800 // end the previous sampling cycle
4801 tracker.stopSampling(ss);
4802 // start a new sampling cycle ..
4803 tracker.startSampling(ss);
4804 }
4805 }
4806 }
4807
4808 log("Done.");
4809
4810 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4811 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4812 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4813
4814 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4815
4816 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
4817 }
4818
4819 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
4820 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
4821 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
4822 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004823}