blob: 6574898028ac505ed8794917552c768504fa811b [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 Deshapndedb7abcb2013-08-21 13:09:01 -070034import android.app.AlarmManager;
Wink Saville690cb182013-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 Saville89c87b92013-08-29 08:55:16 -070039import android.content.ActivityNotFoundException;
Jeff Sharkeyf2e722a2012-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 Sharkeyf2e722a2012-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 Greenwalt7ddc6c92013-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 Sheriffba8388b2012-08-16 12:49:23 -070050import android.net.CaptivePortalTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080051import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080052import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080053import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070055import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070056import android.net.INetworkPolicyListener;
57import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070058import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070059import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080060import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070061import android.net.LinkProperties.CompareResult;
Jeff Sharkey86dc7a82013-09-10 21:03:27 -070062import android.net.LinkQualityInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070064import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070066import android.net.NetworkInfo.DetailedState;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070067import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070068import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080069import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070070import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070071import android.net.Proxy;
72import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070073import android.net.RouteInfo;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -070074import android.net.SamplingDataTracker;
Jason Monk43324ee2013-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 Saville690cb182013-06-29 21:10:57 -070078import android.os.AsyncTask;
The Android Open Source Project28527d22009-03-03 19:31:44 -080079import android.os.Binder;
Wink Saville8fe05f12013-10-31 06:35:22 -070080import android.os.Build;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040081import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080082import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070083import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070084import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070085import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080086import android.os.Looper;
87import android.os.Message;
Robert Greenwalt030e1d32012-08-21 19:27:00 -070088import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070089import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070090import android.os.PowerManager;
Jeff Sharkey5663b6e2012-09-06 17:54:29 -070091import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070092import android.os.RemoteException;
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 Hackbornbc55bd12012-08-29 18:32:08 -070096import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080097import android.provider.Settings;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -070098import android.security.Credentials;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -070099import android.security.KeyStore;
Wink Saville690cb182013-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 Brubakerccae0d32013-06-14 11:16:51 -0700103import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700104import android.util.SparseIntArray;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700105import android.util.Xml;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800106
Wink Saville690cb182013-06-29 21:10:57 -0700107import com.android.internal.R;
Jason Monk43324ee2013-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 Sharkeyc2a8e402012-08-24 11:17:25 -0700111import com.android.internal.net.VpnProfile;
Wink Saville690cb182013-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;
Andrew Flynn2f158282013-10-11 10:16:31 -0700115import com.android.internal.telephony.TelephonyIntents;
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -0700116import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700117import com.android.internal.util.XmlUtils;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700118import com.android.server.am.BatteryStatsService;
John Spurlock4ba7e412013-06-24 14:20:23 -0400119import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900120import com.android.server.connectivity.Nat464Xlat;
Jason Monk43324ee2013-07-03 17:04:33 -0400121import com.android.server.connectivity.PacManager;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800122import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700123import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700124import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700125import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700126import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700127import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700128
tk.mun093f55c2011-10-13 22:51:57 +0900129import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700130
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700131import org.xmlpull.v1.XmlPullParser;
132import org.xmlpull.v1.XmlPullParserException;
133
134import java.io.File;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800135import java.io.FileDescriptor;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700136import java.io.FileNotFoundException;
137import java.io.FileReader;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700138import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800139import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900140import java.lang.reflect.Constructor;
Wink Saville690cb182013-06-29 21:10:57 -0700141import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700142import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700143import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700144import java.net.InetAddress;
Wink Saville690cb182013-06-29 21:10:57 -0700145import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700146import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700147import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700148import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700149import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700150import java.util.GregorianCalendar;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700151import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700152import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700153import java.util.List;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700154import java.util.Map;
Wink Saville690cb182013-06-29 21:10:57 -0700155import java.util.Random;
Wink Saville89c87b92013-08-29 08:55:16 -0700156import java.util.concurrent.atomic.AtomicBoolean;
Wink Saville690cb182013-06-29 21:10:57 -0700157import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800158
Wink Saville8fe05f12013-10-31 06:35:22 -0700159import javax.net.ssl.HostnameVerifier;
160import javax.net.ssl.HttpsURLConnection;
161import javax.net.ssl.SSLSession;
162
The Android Open Source Project28527d22009-03-03 19:31:44 -0800163/**
164 * @hide
165 */
166public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700167 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800168
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700169 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700170 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800171
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700172 private static final boolean LOGD_RULES = false;
173
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700174 // TODO: create better separation between radio types and network types
175
Robert Greenwalt2034b912009-08-12 16:08:25 -0700176 // how long to wait before switching back to a radio's default network
177 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
178 // system property that can override the above value
179 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
180 "android.telephony.apn-restore";
181
Wink Saville690cb182013-06-29 21:10:57 -0700182 // Default value if FAIL_FAST_TIME_MS is not set
183 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
184 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
185 private static final String FAIL_FAST_TIME_MS =
186 "persist.radio.fail_fast_time_ms";
187
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700188 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
189 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
190
Sreeram Ramachandran2103b572013-08-27 11:41:19 -0700191 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700192
193 private PendingIntent mSampleIntervalElapsedIntent;
194
195 // Set network sampling interval at 12 minutes, this way, even if the timers get
196 // aggregated, it will fire at around 15 minutes, which should allow us to
197 // aggregate this timer with other timers (specially the socket keep alive timers)
198 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
199
200 // start network sampling a minute after booting ...
201 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
202
203 AlarmManager mAlarmManager;
204
Robert Greenwaltbd492212011-05-06 17:10:53 -0700205 // used in recursive route setting to add gateways for the host for which
206 // a host route was requested.
207 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
208
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800209 private Tethering mTethering;
210
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700211 private KeyStore mKeyStore;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700212
Chad Brubakerccae0d32013-06-14 11:16:51 -0700213 @GuardedBy("mVpns")
214 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700215 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700216
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700217 private boolean mLockdownEnabled;
218 private LockdownVpnTracker mLockdownTracker;
219
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900220 private Nat464Xlat mClat;
221
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700222 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
223 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700224 /** Currently active network rules by UID. */
225 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700226 /** Set of ifaces that are costly. */
227 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700228
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229 /**
230 * Sometimes we want to refer to the individual network state
231 * trackers separately, and sometimes we just want to treat them
232 * abstractly.
233 */
234 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700235
Irfan Sheriffba8388b2012-08-16 12:49:23 -0700236 /* Handles captive portal check on a network */
237 private CaptivePortalTracker mCaptivePortalTracker;
238
Robert Greenwalt2034b912009-08-12 16:08:25 -0700239 /**
Wink Saville051a6642011-07-13 13:44:13 -0700240 * The link properties that define the current links
241 */
242 private LinkProperties mCurrentLinkProperties[];
243
244 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700245 * A per Net list of the PID's that requested access to the net
246 * used both as a refcount and for per-PID DNS selection
247 */
Mattias Falkdc919012011-08-23 14:15:13 +0200248 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700249
Robert Greenwalt2034b912009-08-12 16:08:25 -0700250 // priority order of the nettrackers
251 // (excluding dynamically set mNetworkPreference)
252 // TODO - move mNetworkTypePreference into this
253 private int[] mPriorityList;
254
The Android Open Source Project28527d22009-03-03 19:31:44 -0800255 private Context mContext;
256 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700257 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700258 // 0 is full bad, 100 is full good
Wink Saville3e866722013-01-31 00:30:13 +0000259 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700260 private int mDefaultInetConditionPublished = 0;
261 private boolean mInetConditionChangeInFlight = false;
262 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800263
Chia-chi Yehcc844502011-07-14 18:01:57 -0700264 private Object mDnsLock = new Object();
Robert Greenwaltd44340d2013-02-11 15:25:10 -0800265 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800266
267 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700268 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800269
Robert Greenwalt355205c2011-05-10 15:05:02 -0700270 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700271 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700272
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700273 private static final int ENABLED = 1;
274 private static final int DISABLED = 0;
275
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700276 private static final boolean ADD = true;
277 private static final boolean REMOVE = false;
278
279 private static final boolean TO_DEFAULT_TABLE = true;
280 private static final boolean TO_SECONDARY_TABLE = false;
281
Chad Brubaker78850f32013-07-15 16:34:04 -0700282 private static final boolean EXEMPT = true;
283 private static final boolean UNEXEMPT = false;
284
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700285 /**
286 * used internally as a delayed event to make us switch back to the
287 * default network
288 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700289 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700290
291 /**
292 * used internally to change our mobile data enabled flag
293 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700294 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700295
296 /**
297 * used internally to change our network preference setting
298 * arg1 = networkType to prefer
299 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700300 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700301
302 /**
303 * used internally to synchronize inet condition reports
304 * arg1 = networkType
305 * arg2 = condition (0 bad, 100 good)
306 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700307 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700308
309 /**
310 * used internally to mark the end of inet condition hold periods
311 * arg1 = networkType
312 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700313 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700314
315 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700316 * used internally to set enable/disable cellular data
317 * arg1 = ENBALED or DISABLED
318 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700319 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700320
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700321 /**
322 * used internally to clear a wakelock when transitioning
323 * from one net to another
324 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700325 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700326
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700327 /**
328 * used internally to reload global proxy settings
329 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700330 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700331
Robert Greenwalt34848c02011-03-25 13:09:25 -0700332 /**
333 * used internally to set external dependency met/unmet
334 * arg1 = ENABLED (met) or DISABLED (unmet)
335 * arg2 = NetworkType
336 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700337 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700338
Chia-chi Yehcc844502011-07-14 18:01:57 -0700339 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700340 * used internally to send a sticky broadcast delayed.
341 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700342 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700343
Jeff Sharkey805662d2011-08-19 02:24:24 -0700344 /**
345 * Used internally to
346 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
347 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700348 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700349
Chad Brubakera8e81122013-07-23 17:44:41 -0700350 private static final int EVENT_VPN_STATE_CHANGED = 13;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700351
Wink Saville690cb182013-06-29 21:10:57 -0700352 /**
353 * Used internally to disable fail fast of mobile data
354 */
Chad Brubakera8e81122013-07-23 17:44:41 -0700355 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
Wink Saville690cb182013-06-29 21:10:57 -0700356
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700357 /**
358 * user internally to indicate that data sampling interval is up
359 */
360 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
361
Jason Monk445cea82013-10-10 14:02:51 -0400362 /**
363 * PAC manager has received new port.
364 */
365 private static final int EVENT_PROXY_HAS_CHANGED = 16;
366
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700367 /** Handler used for internal events. */
368 private InternalHandler mHandler;
369 /** Handler used for incoming {@link NetworkStateTracker} events. */
370 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700371
372 // list of DeathRecipients used to make sure features are turned off when
373 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500374 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700375
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400376 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800377 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400378
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700379 private PowerManager.WakeLock mNetTransitionWakeLock;
380 private String mNetTransitionWakeLockCausedBy = "";
381 private int mNetTransitionWakeLockSerialNumber;
382 private int mNetTransitionWakeLockTimeout;
383
Robert Greenwalt94daa182010-09-01 11:34:05 -0700384 private InetAddress mDefaultDns;
385
Chad Brubaker78850f32013-07-15 16:34:04 -0700386 // Lock for protecting access to mAddedRoutes and mExemptAddresses
387 private final Object mRoutesLock = new Object();
388
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700389 // this collection is used to refcount the added routes - if there are none left
390 // it's time to remove the route from the route table
Chad Brubaker78850f32013-07-15 16:34:04 -0700391 @GuardedBy("mRoutesLock")
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700392 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
393
Chad Brubaker78850f32013-07-15 16:34:04 -0700394 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
395 // used to handle cleanup of exempt rules
396 @GuardedBy("mRoutesLock")
397 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
398
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700399 // used in DBG mode to track inet condition reports
400 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
401 private ArrayList mInetLog;
402
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700403 // track the current default http proxy - tell the world if we get a new one (real change)
404 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltda77cb12013-04-05 17:14:19 -0700405 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700406 private boolean mDefaultProxyDisabled = false;
407
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700408 // track the global proxy.
409 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700410
Jason Monk43324ee2013-07-03 17:04:33 -0400411 private PacManager mPacManager = null;
412
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700413 private SettingsObserver mSettingsObserver;
414
Robert Greenwalt34848c02011-03-25 13:09:25 -0700415 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700416 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700417
Robert Greenwalt12c44552009-12-07 11:33:18 -0800418 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700419 public int mSimultaneity;
420 public int mType;
421 public RadioAttributes(String init) {
422 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700423 mType = Integer.parseInt(fragments[0]);
424 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700425 }
426 }
427 RadioAttributes[] mRadioAttributes;
428
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700429 // the set of network types that can only be enabled by system/sig apps
430 List mProtectedNetworks;
431
John Spurlock4ba7e412013-06-24 14:20:23 -0400432 private DataConnectionStats mDataConnectionStats;
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700433
Wink Saville690cb182013-06-29 21:10:57 -0700434 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
435
436 TelephonyManager mTelephonyManager;
John Spurlock4ba7e412013-06-24 14:20:23 -0400437
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700438 public ConnectivityService(Context context, INetworkManagementService netd,
439 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700440 // Currently, omitting a NetworkFactory will create one internally
441 // TODO: create here when we have cleaner WiMAX support
442 this(context, netd, statsService, policyManager, null);
443 }
444
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700445 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700446 INetworkStatsService statsService, INetworkPolicyManager policyManager,
447 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800448 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800449
Wink Saville775aad62010-09-02 19:23:52 -0700450 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
451 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700452 mHandler = new InternalHandler(handlerThread.getLooper());
453 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700454
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700455 if (netFactory == null) {
456 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
457 }
458
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800459 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800460 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
461 String id = Settings.Secure.getString(context.getContentResolver(),
462 Settings.Secure.ANDROID_ID);
463 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700464 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800465 SystemProperties.set("net.hostname", name);
466 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800467 }
468
Robert Greenwalt94daa182010-09-01 11:34:05 -0700469 // read our default dns server ip
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700470 String dns = Settings.Global.getString(context.getContentResolver(),
471 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700472 if (dns == null || dns.length() == 0) {
473 dns = context.getResources().getString(
474 com.android.internal.R.string.config_default_dns_server);
475 }
476 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800477 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
478 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800479 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700480 }
481
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700482 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700483 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700484 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700485 mKeyStore = KeyStore.getInstance();
Wink Saville690cb182013-06-29 21:10:57 -0700486 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700487
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700488 try {
489 mPolicyManager.registerListener(mPolicyListener);
490 } catch (RemoteException e) {
491 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700492 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700493 }
494
495 final PowerManager powerManager = (PowerManager) context.getSystemService(
496 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700497 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
498 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
499 com.android.internal.R.integer.config_networkTransitionTimeout);
500
Robert Greenwalt2034b912009-08-12 16:08:25 -0700501 mNetTrackers = new NetworkStateTracker[
502 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700503 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700504
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700505 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700506 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700507
Robert Greenwalt2034b912009-08-12 16:08:25 -0700508 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700509 String[] raStrings = context.getResources().getStringArray(
510 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700511 for (String raString : raStrings) {
512 RadioAttributes r = new RadioAttributes(raString);
Wink Saville70dbdcc2013-07-29 15:00:57 -0700513 if (VDBG) log("raString=" + raString + " r=" + r);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700514 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800515 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700516 continue;
517 }
518 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800519 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700520 r.mType);
521 continue;
522 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700523 mRadioAttributes[r.mType] = r;
524 }
525
Wink Saville23ee8db2013-04-23 14:26:51 -0700526 // TODO: What is the "correct" way to do determine if this is a wifi only device?
527 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
528 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700529 String[] naStrings = context.getResources().getStringArray(
530 com.android.internal.R.array.networkAttributes);
531 for (String naString : naStrings) {
532 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700533 NetworkConfig n = new NetworkConfig(naString);
Wink Saville70dbdcc2013-07-29 15:00:57 -0700534 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Savillef2a62832011-04-07 14:23:45 -0700535 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800536 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700537 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700538 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700539 }
Wink Saville23ee8db2013-04-23 14:26:51 -0700540 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
541 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
542 n.type);
543 continue;
544 }
Wink Savillef2a62832011-04-07 14:23:45 -0700545 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800546 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700547 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700548 continue;
549 }
Wink Savillef2a62832011-04-07 14:23:45 -0700550 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800551 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700552 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700553 continue;
554 }
Wink Savillef2a62832011-04-07 14:23:45 -0700555 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700556 mNetworksDefined++;
557 } catch(Exception e) {
558 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700559 }
560 }
Wink Saville70dbdcc2013-07-29 15:00:57 -0700561 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700562
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700563 mProtectedNetworks = new ArrayList<Integer>();
564 int[] protectedNetworks = context.getResources().getIntArray(
565 com.android.internal.R.array.config_protectedNetworks);
566 for (int p : protectedNetworks) {
567 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
568 mProtectedNetworks.add(p);
569 } else {
570 if (DBG) loge("Ignoring protectedNetwork " + p);
571 }
572 }
573
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700574 // high priority first
575 mPriorityList = new int[mNetworksDefined];
576 {
577 int insertionPoint = mNetworksDefined-1;
578 int currentLowest = 0;
579 int nextLowest = 0;
580 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700581 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700582 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700583 if (na.priority < currentLowest) continue;
584 if (na.priority > currentLowest) {
585 if (na.priority < nextLowest || nextLowest == 0) {
586 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700587 }
588 continue;
589 }
Wink Savillef2a62832011-04-07 14:23:45 -0700590 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700591 }
592 currentLowest = nextLowest;
593 nextLowest = 0;
594 }
595 }
596
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800597 // Update mNetworkPreference according to user mannually first then overlay config.xml
598 mNetworkPreference = getPersistedNetworkPreference();
599 if (mNetworkPreference == -1) {
600 for (int n : mPriorityList) {
601 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
602 mNetworkPreference = n;
603 break;
604 }
605 }
606 if (mNetworkPreference == -1) {
607 throw new IllegalStateException(
608 "You should set at least one default Network in config.xml!");
609 }
610 }
611
Mattias Falkdc919012011-08-23 14:15:13 +0200612 mNetRequestersPids =
613 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700614 for (int i : mPriorityList) {
Mattias Falkdc919012011-08-23 14:15:13 +0200615 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700616 }
617
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500618 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700619
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700620 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
621 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700622
623 // Create and start trackers for hard-coded networks
624 for (int targetNetworkType : mPriorityList) {
625 final NetworkConfig config = mNetConfigs[targetNetworkType];
626 final NetworkStateTracker tracker;
627 try {
628 tracker = netFactory.createTracker(targetNetworkType, config);
629 mNetTrackers[targetNetworkType] = tracker;
630 } catch (IllegalArgumentException e) {
631 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
632 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700633 continue;
634 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700635
636 tracker.startMonitoring(context, mTrackerHandler);
637 if (config.isDefault()) {
638 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800639 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700640 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800641
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700642 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800643
Robert Greenwalt00eb17f2013-07-19 14:30:49 -0700644 //set up the listener for user state for creating user VPNs
Chad Brubakerccae0d32013-06-14 11:16:51 -0700645 IntentFilter intentFilter = new IntentFilter();
646 intentFilter.addAction(Intent.ACTION_USER_STARTING);
647 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
648 mContext.registerReceiverAsUser(
649 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900650 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
651
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700652 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700653 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700654 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900655 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700656 } catch (RemoteException e) {
657 loge("Error registering observer :" + e);
658 }
659
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700660 if (DBG) {
661 mInetLog = new ArrayList();
662 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700663
664 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
665 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800666
John Spurlock4ba7e412013-06-24 14:20:23 -0400667 mDataConnectionStats = new DataConnectionStats(mContext);
668 mDataConnectionStats.startMonitoring();
Jason Monk43324ee2013-07-03 17:04:33 -0400669
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700670 // start network sampling ..
671 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
672 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
Sreeram Ramachandran2103b572013-08-27 11:41:19 -0700673 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -0700674
675 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
676 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
677
678 IntentFilter filter = new IntentFilter();
679 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
680 mContext.registerReceiver(
681 new BroadcastReceiver() {
682 @Override
683 public void onReceive(Context context, Intent intent) {
684 String action = intent.getAction();
685 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
686 mHandler.sendMessage(mHandler.obtainMessage
687 (EVENT_SAMPLE_INTERVAL_ELAPSED));
688 }
689 }
690 },
691 new IntentFilter(filter));
692
Jason Monk445cea82013-10-10 14:02:51 -0400693 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville3ade4872013-08-29 14:57:08 -0700694
695 filter = new IntentFilter();
Wink Saville89c87b92013-08-29 08:55:16 -0700696 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
697 mContext.registerReceiver(mProvisioningReceiver, filter);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800698 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700699
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700700 /**
701 * Factory that creates {@link NetworkStateTracker} instances using given
702 * {@link NetworkConfig}.
703 */
704 public interface NetworkFactory {
705 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
706 }
707
708 private static class DefaultNetworkFactory implements NetworkFactory {
709 private final Context mContext;
710 private final Handler mTrackerHandler;
711
712 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
713 mContext = context;
714 mTrackerHandler = trackerHandler;
715 }
716
717 @Override
718 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
719 switch (config.radio) {
720 case TYPE_WIFI:
721 return new WifiStateTracker(targetNetworkType, config.name);
722 case TYPE_MOBILE:
723 return new MobileDataStateTracker(targetNetworkType, config.name);
724 case TYPE_DUMMY:
725 return new DummyDataStateTracker(targetNetworkType, config.name);
726 case TYPE_BLUETOOTH:
727 return BluetoothTetheringDataTracker.getInstance();
728 case TYPE_WIMAX:
729 return makeWimaxStateTracker(mContext, mTrackerHandler);
730 case TYPE_ETHERNET:
731 return EthernetDataTracker.getInstance();
732 default:
733 throw new IllegalArgumentException(
734 "Trying to create a NetworkStateTracker for an unknown radio type: "
735 + config.radio);
736 }
737 }
738 }
739
740 /**
741 * Loads external WiMAX library and registers as system service, returning a
742 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
743 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
744 */
745 private static NetworkStateTracker makeWimaxStateTracker(
746 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700747 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900748 DexClassLoader wimaxClassLoader;
749 Class wimaxStateTrackerClass = null;
750 Class wimaxServiceClass = null;
751 Class wimaxManagerClass;
752 String wimaxJarLocation;
753 String wimaxLibLocation;
754 String wimaxManagerClassName;
755 String wimaxServiceClassName;
756 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800757
tk.mun093f55c2011-10-13 22:51:57 +0900758 NetworkStateTracker wimaxStateTracker = null;
759
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700760 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900761 com.android.internal.R.bool.config_wimaxEnabled);
762
763 if (isWimaxEnabled) {
764 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700765 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900766 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700767 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900768 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700769 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900770 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700771 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900772 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700773 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900774 com.android.internal.R.string.config_wimaxStateTrackerClassname);
775
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800776 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900777 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700778 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900779 wimaxLibLocation, ClassLoader.getSystemClassLoader());
780
781 try {
782 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
783 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
784 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
785 } catch (ClassNotFoundException ex) {
786 loge("Exception finding Wimax classes: " + ex.toString());
787 return null;
788 }
789 } catch(Resources.NotFoundException ex) {
790 loge("Wimax Resources does not exist!!! ");
791 return null;
792 }
793
794 try {
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800795 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900796
797 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
798 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700799 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
800 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900801
802 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
803 (new Class[] {Context.class, wimaxStateTrackerClass});
804 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700805 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900806 wmxSrvConst.setAccessible(false);
807
808 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
809
810 } catch(Exception ex) {
811 loge("Exception creating Wimax classes: " + ex.toString());
812 return null;
813 }
814 } else {
815 loge("Wimax is not enabled or not added to the network attributes!!! ");
816 return null;
817 }
818
819 return wimaxStateTracker;
820 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700821
The Android Open Source Project28527d22009-03-03 19:31:44 -0800822 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700823 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800824 * @param preference the new preference
825 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700826 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800827 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700828
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700829 mHandler.sendMessage(
830 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800831 }
832
833 public int getNetworkPreference() {
834 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700835 int preference;
836 synchronized(this) {
837 preference = mNetworkPreference;
838 }
839 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800840 }
841
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700842 private void handleSetNetworkPreference(int preference) {
843 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700844 mNetConfigs[preference] != null &&
845 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700846 if (mNetworkPreference != preference) {
847 final ContentResolver cr = mContext.getContentResolver();
Jeff Brown87272712012-09-25 15:03:20 -0700848 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700849 synchronized(this) {
850 mNetworkPreference = preference;
851 }
852 enforcePreference();
853 }
854 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800855 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700856
Wink Saville4f0de1e2011-08-04 15:01:58 -0700857 private int getConnectivityChangeDelay() {
858 final ContentResolver cr = mContext.getContentResolver();
859
860 /** Check system properties for the default value then use secure settings value, if any. */
861 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700862 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
863 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
864 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700865 defaultDelay);
866 }
867
The Android Open Source Project28527d22009-03-03 19:31:44 -0800868 private int getPersistedNetworkPreference() {
869 final ContentResolver cr = mContext.getContentResolver();
870
Jeff Brown87272712012-09-25 15:03:20 -0700871 final int networkPrefSetting = Settings.Global
872 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800873
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800874 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800875 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700876
The Android Open Source Project28527d22009-03-03 19:31:44 -0800877 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700878 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800879 * In this method, we only tear down a non-preferred network. Establishing
880 * a connection to the preferred network is taken care of when we handle
881 * the disconnect event from the non-preferred network
882 * (see {@link #handleDisconnect(NetworkInfo)}).
883 */
884 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700885 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800886 return;
887
Robert Greenwalt2034b912009-08-12 16:08:25 -0700888 if (!mNetTrackers[mNetworkPreference].isAvailable())
889 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800890
Robert Greenwalt2034b912009-08-12 16:08:25 -0700891 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700892 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700893 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700894 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800895 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700896 " in enforcePreference");
897 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700898 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800899 }
900 }
901 }
902
903 private boolean teardown(NetworkStateTracker netTracker) {
904 if (netTracker.teardown()) {
905 netTracker.setTeardownRequested(true);
906 return true;
907 } else {
908 return false;
909 }
910 }
911
912 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700913 * Check if UID should be blocked from using the network represented by the
914 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700915 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700916 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
917 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700918
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700919 final boolean networkCostly;
920 final int uidRules;
921 synchronized (mRulesLock) {
922 networkCostly = mMeteredIfaces.contains(iface);
923 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700924 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700925
926 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
927 return true;
928 }
929
930 // no restrictive rules; network is visible
931 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700932 }
933
934 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700935 * Return a filtered {@link NetworkInfo}, potentially marked
936 * {@link DetailedState#BLOCKED} based on
937 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700938 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700939 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
940 NetworkInfo info = tracker.getNetworkInfo();
941 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700942 // network is blocked; clone and override state
943 info = new NetworkInfo(info);
944 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700945 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700946 if (mLockdownTracker != null) {
947 info = mLockdownTracker.augmentNetworkInfo(info);
948 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700949 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700950 }
951
952 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800953 * Return NetworkInfo for the active (i.e., connected) network interface.
954 * It is assumed that at most one network is active at a time. If more
955 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700956 * @return the info for the active network, or {@code null} if none is
957 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800958 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700959 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800960 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700961 enforceAccessPermission();
962 final int uid = Binder.getCallingUid();
963 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800964 }
965
Wink Saville89c87b92013-08-29 08:55:16 -0700966 /**
967 * Find the first Provisioning network.
968 *
969 * @return NetworkInfo or null if none.
970 */
971 private NetworkInfo getProvisioningNetworkInfo() {
972 enforceAccessPermission();
973
974 // Find the first Provisioning Network
975 NetworkInfo provNi = null;
976 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville860f5282013-09-05 12:02:25 -0700977 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -0700978 provNi = ni;
979 break;
980 }
981 }
982 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
983 return provNi;
984 }
985
986 /**
987 * Find the first Provisioning network or the ActiveDefaultNetwork
988 * if there is no Provisioning network
989 *
990 * @return NetworkInfo or null if none.
991 */
992 @Override
993 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
994 enforceAccessPermission();
995
996 NetworkInfo provNi = getProvisioningNetworkInfo();
997 if (provNi == null) {
998 final int uid = Binder.getCallingUid();
999 provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
1000 }
1001 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
1002 return provNi;
1003 }
1004
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001005 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1006 enforceAccessPermission();
1007 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
1008 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
1009 if (tracker != null) {
1010 return tracker.getNetworkInfo();
1011 }
1012 }
1013 return null;
1014 }
1015
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001016 @Override
1017 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1018 enforceConnectivityInternalPermission();
1019 return getNetworkInfo(mActiveDefaultNetwork, uid);
1020 }
1021
1022 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001023 public NetworkInfo getNetworkInfo(int networkType) {
1024 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001025 final int uid = Binder.getCallingUid();
1026 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001027 }
1028
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001029 private NetworkInfo getNetworkInfo(int networkType, int uid) {
1030 NetworkInfo info = null;
1031 if (isNetworkTypeValid(networkType)) {
1032 final NetworkStateTracker tracker = mNetTrackers[networkType];
1033 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001034 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001035 }
1036 }
1037 return info;
1038 }
1039
1040 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001041 public NetworkInfo[] getAllNetworkInfo() {
1042 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001043 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -07001044 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001045 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001046 for (NetworkStateTracker tracker : mNetTrackers) {
1047 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001048 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001049 }
1050 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001051 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001052 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001053 }
1054
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001055 @Override
1056 public boolean isNetworkSupported(int networkType) {
1057 enforceAccessPermission();
1058 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
1059 }
1060
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001061 /**
1062 * Return LinkProperties for the active (i.e., connected) default
1063 * network interface. It is assumed that at most one default network
1064 * is active at a time. If more than one is active, it is indeterminate
1065 * which will be returned.
1066 * @return the ip properties for the active network, or {@code null} if
1067 * none is active
1068 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001069 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001070 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -07001071 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001072 }
1073
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001074 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001075 public LinkProperties getLinkProperties(int networkType) {
1076 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001077 if (isNetworkTypeValid(networkType)) {
1078 final NetworkStateTracker tracker = mNetTrackers[networkType];
1079 if (tracker != null) {
1080 return tracker.getLinkProperties();
1081 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001082 }
1083 return null;
1084 }
1085
Jeff Sharkey21062e72011-05-28 20:56:34 -07001086 @Override
1087 public NetworkState[] getAllNetworkState() {
1088 enforceAccessPermission();
1089 final int uid = Binder.getCallingUid();
1090 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001091 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -07001092 for (NetworkStateTracker tracker : mNetTrackers) {
1093 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001094 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -07001095 result.add(new NetworkState(
1096 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
1097 }
1098 }
1099 }
1100 return result.toArray(new NetworkState[result.size()]);
1101 }
1102
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001103 private NetworkState getNetworkStateUnchecked(int networkType) {
1104 if (isNetworkTypeValid(networkType)) {
1105 final NetworkStateTracker tracker = mNetTrackers[networkType];
1106 if (tracker != null) {
1107 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
1108 tracker.getLinkCapabilities());
1109 }
1110 }
1111 return null;
1112 }
1113
1114 @Override
1115 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1116 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001117
1118 final long token = Binder.clearCallingIdentity();
1119 try {
1120 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1121 if (state != null) {
1122 try {
1123 return mPolicyManager.getNetworkQuotaInfo(state);
1124 } catch (RemoteException e) {
1125 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001126 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001127 return null;
1128 } finally {
1129 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001130 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001131 }
1132
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001133 @Override
1134 public boolean isActiveNetworkMetered() {
1135 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001136 final long token = Binder.clearCallingIdentity();
1137 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001138 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001139 } finally {
1140 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001141 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001142 }
1143
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001144 private boolean isNetworkMeteredUnchecked(int networkType) {
1145 final NetworkState state = getNetworkStateUnchecked(networkType);
1146 if (state != null) {
1147 try {
1148 return mPolicyManager.isNetworkMetered(state);
1149 } catch (RemoteException e) {
1150 }
1151 }
1152 return false;
1153 }
1154
The Android Open Source Project28527d22009-03-03 19:31:44 -08001155 public boolean setRadios(boolean turnOn) {
1156 boolean result = true;
1157 enforceChangePermission();
1158 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001159 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001160 }
1161 return result;
1162 }
1163
1164 public boolean setRadio(int netType, boolean turnOn) {
1165 enforceChangePermission();
1166 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1167 return false;
1168 }
1169 NetworkStateTracker tracker = mNetTrackers[netType];
1170 return tracker != null && tracker.setRadio(turnOn);
1171 }
1172
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001173 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1174 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001175 public void interfaceClassDataActivityChanged(String label, boolean active) {
1176 int deviceType = Integer.parseInt(label);
1177 sendDataActivityBroadcast(deviceType, active);
1178 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001179 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001180
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001181 /**
1182 * Used to notice when the calling process dies so we can self-expire
1183 *
1184 * Also used to know if the process has cleaned up after itself when
1185 * our auto-expire timer goes off. The timer has a link to an object.
1186 *
1187 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001188 private class FeatureUser implements IBinder.DeathRecipient {
1189 int mNetworkType;
1190 String mFeature;
1191 IBinder mBinder;
1192 int mPid;
1193 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001194 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001195
1196 FeatureUser(int type, String feature, IBinder binder) {
1197 super();
1198 mNetworkType = type;
1199 mFeature = feature;
1200 mBinder = binder;
1201 mPid = getCallingPid();
1202 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001203 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001204
Robert Greenwalt2034b912009-08-12 16:08:25 -07001205 try {
1206 mBinder.linkToDeath(this, 0);
1207 } catch (RemoteException e) {
1208 binderDied();
1209 }
1210 }
1211
1212 void unlinkDeathRecipient() {
1213 mBinder.unlinkToDeath(this, 0);
1214 }
1215
1216 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001217 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001218 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1219 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001220 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001221 }
1222
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001223 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001224 if (VDBG) {
1225 log("ConnectivityService FeatureUser expire(" +
1226 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1227 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1228 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001229 stopUsingNetworkFeature(this, false);
1230 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001231
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001232 public boolean isSameUser(FeatureUser u) {
1233 if (u == null) return false;
1234
1235 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1236 }
1237
1238 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1239 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1240 TextUtils.equals(mFeature, feature)) {
1241 return true;
1242 }
1243 return false;
1244 }
1245
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001246 public String toString() {
1247 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1248 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1249 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001250 }
1251
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001252 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001253 public int startUsingNetworkFeature(int networkType, String feature,
1254 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001255 long startTime = 0;
1256 if (DBG) {
1257 startTime = SystemClock.elapsedRealtime();
1258 }
Wink Savillea7d56572011-09-21 11:05:43 -07001259 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001260 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1261 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001262 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001263 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001264 try {
1265 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1266 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001267 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001268 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001269
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001270 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001271
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001272 // TODO - move this into individual networktrackers
1273 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001274
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001275 if (mLockdownEnabled) {
1276 // Since carrier APNs usually aren't available from VPN
1277 // endpoint, mark them as unavailable.
1278 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1279 }
1280
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001281 if (mProtectedNetworks.contains(usedNetworkType)) {
1282 enforceConnectivityInternalPermission();
1283 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001284
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001285 // if UID is restricted, don't allow them to bring up metered APNs
1286 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1287 final int uidRules;
1288 synchronized (mRulesLock) {
1289 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1290 }
1291 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001292 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001293 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001294
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001295 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1296 if (network != null) {
1297 Integer currentPid = new Integer(getCallingPid());
1298 if (usedNetworkType != networkType) {
1299 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001300
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001301 if (ni.isAvailable() == false) {
1302 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1303 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001304 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001305 } else {
1306 // else make the attempt anyway - probably giving REQUEST_STARTED below
1307 if (DBG) {
1308 log("special network not available, but try anyway ni=" +
1309 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001310 }
1311 }
1312 }
1313
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001314 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001315
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001316 synchronized(this) {
1317 boolean addToList = true;
1318 if (restoreTimer < 0) {
1319 // In case there is no timer is specified for the feature,
1320 // make sure we don't add duplicate entry with the same request.
1321 for (FeatureUser u : mFeatureUsers) {
1322 if (u.isSameUser(f)) {
1323 // Duplicate user is found. Do not add.
1324 addToList = false;
1325 break;
1326 }
1327 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001328 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001329
1330 if (addToList) mFeatureUsers.add(f);
1331 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1332 // this gets used for per-pid dns when connected
1333 mNetRequestersPids[usedNetworkType].add(currentPid);
1334 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001335 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001336
1337 if (restoreTimer >= 0) {
1338 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1339 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1340 }
1341
1342 if ((ni.isConnectedOrConnecting() == true) &&
1343 !network.isTeardownRequested()) {
1344 if (ni.isConnected() == true) {
1345 final long token = Binder.clearCallingIdentity();
1346 try {
1347 // add the pid-specific dns
1348 handleDnsConfigurationChange(usedNetworkType);
1349 if (VDBG) log("special network already active");
1350 } finally {
1351 Binder.restoreCallingIdentity(token);
1352 }
Wink Saville64e3f782012-07-10 12:37:54 -07001353 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001354 }
1355 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001356 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001357 }
1358
1359 // check if the radio in play can make another contact
1360 // assume if cannot for now
1361
1362 if (DBG) {
1363 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1364 feature);
1365 }
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001366 if (network.reconnect()) {
Wink Saville89c87b92013-08-29 08:55:16 -07001367 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001368 return PhoneConstants.APN_REQUEST_STARTED;
1369 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07001370 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001371 return PhoneConstants.APN_REQUEST_FAILED;
1372 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001373 } else {
1374 // need to remember this unsupported request so we respond appropriately on stop
1375 synchronized(this) {
1376 mFeatureUsers.add(f);
1377 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1378 // this gets used for per-pid dns when connected
1379 mNetRequestersPids[usedNetworkType].add(currentPid);
1380 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001381 }
Wink Saville89c87b92013-08-29 08:55:16 -07001382 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001383 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001384 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001385 }
Wink Saville89c87b92013-08-29 08:55:16 -07001386 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
Wink Saville64e3f782012-07-10 12:37:54 -07001387 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001388 } finally {
1389 if (DBG) {
1390 final long execTime = SystemClock.elapsedRealtime() - startTime;
1391 if (execTime > 250) {
1392 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1393 } else {
1394 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1395 }
1396 }
1397 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001398 }
1399
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001400 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001401 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001402 enforceChangePermission();
1403
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001404 int pid = getCallingPid();
1405 int uid = getCallingUid();
1406
1407 FeatureUser u = null;
1408 boolean found = false;
1409
1410 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001411 for (FeatureUser x : mFeatureUsers) {
1412 if (x.isSameUser(pid, uid, networkType, feature)) {
1413 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001414 found = true;
1415 break;
1416 }
1417 }
1418 }
1419 if (found && u != null) {
Wink Saville89c87b92013-08-29 08:55:16 -07001420 if (VDBG) log("stopUsingNetworkFeature: X");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001421 // stop regardless of how many other time this proc had called start
1422 return stopUsingNetworkFeature(u, true);
1423 } else {
1424 // none found!
Wink Saville89c87b92013-08-29 08:55:16 -07001425 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001426 return 1;
1427 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001428 }
1429
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001430 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1431 int networkType = u.mNetworkType;
1432 String feature = u.mFeature;
1433 int pid = u.mPid;
1434 int uid = u.mUid;
1435
1436 NetworkStateTracker tracker = null;
1437 boolean callTeardown = false; // used to carry our decision outside of sync block
1438
Wink Savillea7d56572011-09-21 11:05:43 -07001439 if (VDBG) {
1440 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001441 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001442
The Android Open Source Project28527d22009-03-03 19:31:44 -08001443 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001444 if (DBG) {
1445 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1446 ", net is invalid");
1447 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001448 return -1;
1449 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001450
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001451 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1452 // sync block
1453 synchronized(this) {
1454 // check if this process still has an outstanding start request
1455 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001456 if (VDBG) {
1457 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1458 ", ignoring");
1459 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001460 return 1;
1461 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001462 u.unlinkDeathRecipient();
1463 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1464 // If we care about duplicate requests, check for that here.
1465 //
1466 // This is done to support the extension of a request - the app
1467 // can request we start the network feature again and renew the
1468 // auto-shutoff delay. Normal "stop" calls from the app though
1469 // do not pay attention to duplicate requests - in effect the
1470 // API does not refcount and a single stop will counter multiple starts.
1471 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001472 for (FeatureUser x : mFeatureUsers) {
1473 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001474 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001475 return 1;
1476 }
1477 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001478 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001479
repo syncf5de5572011-07-29 23:55:49 -07001480 // TODO - move to individual network trackers
1481 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1482
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001483 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001484 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001485 if (DBG) {
1486 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1487 " no known tracker for used net type " + usedNetworkType);
1488 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001489 return -1;
1490 }
1491 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001492 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001493 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt17900092013-02-12 17:18:25 -08001494
1495 final long token = Binder.clearCallingIdentity();
1496 try {
1497 reassessPidDns(pid, true);
1498 } finally {
1499 Binder.restoreCallingIdentity(token);
1500 }
Mattias Falkdc919012011-08-23 14:15:13 +02001501 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001502 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001503 if (VDBG) {
1504 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1505 " others still using it");
1506 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001507 return 1;
1508 }
1509 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001510 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001511 if (DBG) {
1512 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1513 " not a known feature - dropping");
1514 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001515 }
1516 }
Wink Savillea7d56572011-09-21 11:05:43 -07001517
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001518 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001519 if (DBG) {
1520 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1521 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001522 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001523 return 1;
1524 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001525 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001526 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001527 }
1528
1529 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001530 * @deprecated use requestRouteToHostAddress instead
1531 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001532 * Ensure that a network route exists to deliver traffic to the specified
1533 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001534 * @param networkType the type of the network over which traffic to the
1535 * specified host is to be routed
1536 * @param hostAddress the IP address of the host to which the route is
1537 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001538 * @return {@code true} on success, {@code false} on failure
1539 */
1540 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001541 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1542
1543 if (inetAddress == null) {
1544 return false;
1545 }
1546
1547 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1548 }
1549
1550 /**
1551 * Ensure that a network route exists to deliver traffic to the specified
1552 * host via the specified network interface.
1553 * @param networkType the type of the network over which traffic to the
1554 * specified host is to be routed
1555 * @param hostAddress the IP address of the host to which the route is
1556 * desired
1557 * @return {@code true} on success, {@code false} on failure
1558 */
1559 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001560 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001561 if (mProtectedNetworks.contains(networkType)) {
1562 enforceConnectivityInternalPermission();
1563 }
1564
The Android Open Source Project28527d22009-03-03 19:31:44 -08001565 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001566 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001567 return false;
1568 }
1569 NetworkStateTracker tracker = mNetTrackers[networkType];
Ken Mixter7caa36a2013-11-07 22:08:24 -08001570 DetailedState netState = DetailedState.DISCONNECTED;
1571 if (tracker != null) {
1572 netState = tracker.getNetworkInfo().getDetailedState();
1573 }
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001574
Ken Mixter7caa36a2013-11-07 22:08:24 -08001575 if ((netState != DetailedState.CONNECTED &&
Irfan Sheriffba8388b2012-08-16 12:49:23 -07001576 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001577 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001578 if (VDBG) {
Wink Saville690cb182013-06-29 21:10:57 -07001579 log("requestRouteToHostAddress on down network "
1580 + "(" + networkType + ") - dropped"
1581 + " tracker=" + tracker
1582 + " netState=" + netState
1583 + " isTeardownRequested="
1584 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001585 }
1586 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001587 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001588 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001589 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001590 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001591 LinkProperties lp = tracker.getLinkProperties();
Chad Brubaker78850f32013-07-15 16:34:04 -07001592 boolean ok = addRouteToAddress(lp, addr, EXEMPT);
Wink Saville690cb182013-06-29 21:10:57 -07001593 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1594 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001595 } catch (UnknownHostException e) {
1596 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1597 } finally {
1598 Binder.restoreCallingIdentity(token);
1599 }
Wink Saville690cb182013-06-29 21:10:57 -07001600 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001601 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001602 }
1603
Chad Brubaker78850f32013-07-15 16:34:04 -07001604 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1605 boolean exempt) {
1606 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001607 }
1608
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001609 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001610 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001611 }
1612
Chad Brubaker78850f32013-07-15 16:34:04 -07001613 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
1614 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001615 }
1616
1617 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001618 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
Robert Greenwalt98107422011-07-22 11:55:33 -07001619 }
1620
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001621 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
Chad Brubaker78850f32013-07-15 16:34:04 -07001622 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001623 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001624 if (bestRoute == null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001625 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001626 } else {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001627 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001628 if (bestRoute.getGateway().equals(addr)) {
1629 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001630 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001631 } else {
1632 // if we will connect to this through another route, add a direct route
1633 // to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001634 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001635 }
1636 }
Chad Brubaker78850f32013-07-15 16:34:04 -07001637 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07001638 }
1639
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001640 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
Chad Brubaker78850f32013-07-15 16:34:04 -07001641 boolean toDefaultTable, boolean exempt) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001642 if ((lp == null) || (r == null)) {
1643 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001644 return false;
1645 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001646
1647 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001648 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001649 return false;
1650 }
1651
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001652 String ifaceName = r.getInterface();
1653 if(ifaceName == null) {
1654 loge("Error modifying route - no interface name");
1655 return false;
1656 }
Robert Greenwalt24bc5342013-04-11 13:48:16 -07001657 if (r.hasGateway()) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001658 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001659 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001660 if (bestRoute.getGateway().equals(r.getGateway())) {
1661 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001662 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001663 } else {
1664 // if we will connect to our gateway through another route, add a direct
1665 // route to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001666 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1667 bestRoute.getGateway(),
1668 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001669 }
Chad Brubaker78850f32013-07-15 16:34:04 -07001670 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001671 }
1672 }
1673 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001674 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001675 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001676 if (toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001677 synchronized (mRoutesLock) {
1678 // only track default table - only one apps can effect
1679 mAddedRoutes.add(r);
1680 mNetd.addRoute(ifaceName, r);
1681 if (exempt) {
1682 LinkAddress dest = r.getDestination();
1683 if (!mExemptAddresses.contains(dest)) {
1684 mNetd.setHostExemption(dest);
1685 mExemptAddresses.add(dest);
1686 }
1687 }
1688 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001689 } else {
1690 mNetd.addSecondaryRoute(ifaceName, r);
1691 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001692 } catch (Exception e) {
1693 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001694 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001695 return false;
1696 }
1697 } else {
1698 // if we remove this one and there are no more like it, then refcount==0 and
1699 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001700 if (toDefaultTable) {
Chad Brubaker78850f32013-07-15 16:34:04 -07001701 synchronized (mRoutesLock) {
1702 mAddedRoutes.remove(r);
1703 if (mAddedRoutes.contains(r) == false) {
1704 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1705 try {
1706 mNetd.removeRoute(ifaceName, r);
1707 LinkAddress dest = r.getDestination();
1708 if (mExemptAddresses.contains(dest)) {
1709 mNetd.clearHostExemption(dest);
1710 mExemptAddresses.remove(dest);
1711 }
1712 } catch (Exception e) {
1713 // never crash - catch them all
1714 if (VDBG) loge("Exception trying to remove a route: " + e);
1715 return false;
1716 }
1717 } else {
1718 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001719 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001720 }
1721 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001722 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001723 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001724 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001725 } catch (Exception e) {
1726 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001727 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001728 return false;
1729 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001730 }
1731 }
1732 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001733 }
1734
1735 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001736 * @see ConnectivityManager#getMobileDataEnabled()
1737 */
1738 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001739 // TODO: This detail should probably be in DataConnectionTracker's
1740 // which is where we store the value and maybe make this
1741 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001742 enforceAccessPermission();
Jeff Sharkey9ee49b32012-09-26 15:54:06 -07001743 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1744 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001745 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001746 return retVal;
1747 }
1748
Robert Greenwalt34848c02011-03-25 13:09:25 -07001749 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001750 enforceConnectivityInternalPermission();
1751
Robert Greenwalt34848c02011-03-25 13:09:25 -07001752 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1753 (met ? ENABLED : DISABLED), networkType));
1754 }
1755
1756 private void handleSetDependencyMet(int networkType, boolean met) {
1757 if (mNetTrackers[networkType] != null) {
1758 if (DBG) {
1759 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1760 }
1761 mNetTrackers[networkType].setDependencyMet(met);
1762 }
1763 }
1764
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001765 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1766 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001767 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001768 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001769 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001770 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001771 }
1772
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001773 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001774 // skip update when we've already applied rules
1775 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1776 if (oldRules == uidRules) return;
1777
1778 mUidRules.put(uid, uidRules);
1779 }
1780
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001781 // TODO: notify UID when it has requested targeted updates
1782 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001783
1784 @Override
1785 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001786 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001787 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001788 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001789 }
1790
1791 synchronized (mRulesLock) {
1792 mMeteredIfaces.clear();
1793 for (String iface : meteredIfaces) {
1794 mMeteredIfaces.add(iface);
1795 }
1796 }
1797 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001798
1799 @Override
1800 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1801 // caller is NPMS, since we only register with them
1802 if (LOGD_RULES) {
1803 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1804 }
1805
1806 // kick off connectivity change broadcast for active network, since
1807 // global background policy change is radical.
1808 final int networkType = mActiveDefaultNetwork;
1809 if (isNetworkTypeValid(networkType)) {
1810 final NetworkStateTracker tracker = mNetTrackers[networkType];
1811 if (tracker != null) {
1812 final NetworkInfo info = tracker.getNetworkInfo();
1813 if (info != null && info.isConnected()) {
1814 sendConnectedBroadcast(info);
1815 }
1816 }
1817 }
1818 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001819 };
1820
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001821 /**
1822 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1823 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001824 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001825 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001826 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001827
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001828 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001829 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001830 }
1831
1832 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001833 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001834 if (VDBG) {
1835 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001836 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001837 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1838 }
tk.mun5eee1042012-01-06 10:43:52 +09001839 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1840 if (VDBG) {
1841 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1842 }
1843 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1844 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001845 }
1846
1847 @Override
1848 public void setPolicyDataEnable(int networkType, boolean enabled) {
1849 // only someone like NPMS should only be calling us
1850 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1851
1852 mHandler.sendMessage(mHandler.obtainMessage(
1853 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1854 }
1855
1856 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1857 if (isNetworkTypeValid(networkType)) {
1858 final NetworkStateTracker tracker = mNetTrackers[networkType];
1859 if (tracker != null) {
1860 tracker.setPolicyDataEnable(enabled);
1861 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001862 }
1863 }
1864
The Android Open Source Project28527d22009-03-03 19:31:44 -08001865 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001866 mContext.enforceCallingOrSelfPermission(
1867 android.Manifest.permission.ACCESS_NETWORK_STATE,
1868 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001869 }
1870
1871 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001872 mContext.enforceCallingOrSelfPermission(
1873 android.Manifest.permission.CHANGE_NETWORK_STATE,
1874 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001875 }
1876
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001877 // TODO Make this a special check when it goes public
1878 private void enforceTetherChangePermission() {
1879 mContext.enforceCallingOrSelfPermission(
1880 android.Manifest.permission.CHANGE_NETWORK_STATE,
1881 "ConnectivityService");
1882 }
1883
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001884 private void enforceTetherAccessPermission() {
1885 mContext.enforceCallingOrSelfPermission(
1886 android.Manifest.permission.ACCESS_NETWORK_STATE,
1887 "ConnectivityService");
1888 }
1889
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001890 private void enforceConnectivityInternalPermission() {
1891 mContext.enforceCallingOrSelfPermission(
1892 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1893 "ConnectivityService");
1894 }
1895
Chad Brubaker31de0b62013-07-11 13:29:30 -07001896 private void enforceMarkNetworkSocketPermission() {
1897 //Media server special case
1898 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1899 return;
1900 }
1901 mContext.enforceCallingOrSelfPermission(
1902 android.Manifest.permission.MARK_NETWORK_SOCKET,
1903 "ConnectivityService");
1904 }
1905
The Android Open Source Project28527d22009-03-03 19:31:44 -08001906 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001907 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1908 * network, we ignore it. If it is for the active network, we send out a
1909 * broadcast. But first, we check whether it might be possible to connect
1910 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001911 * @param info the {@code NetworkInfo} for the network
1912 */
1913 private void handleDisconnect(NetworkInfo info) {
1914
Robert Greenwalt2034b912009-08-12 16:08:25 -07001915 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001916
Robert Greenwalt2034b912009-08-12 16:08:25 -07001917 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai92e03a72012-06-28 15:26:19 -07001918
1919 // Remove idletimer previously setup in {@code handleConnect}
1920 removeDataActivityTracking(prevNetType);
1921
The Android Open Source Project28527d22009-03-03 19:31:44 -08001922 /*
1923 * If the disconnected network is not the active one, then don't report
1924 * this as a loss of connectivity. What probably happened is that we're
1925 * getting the disconnect for a network that we explicitly disabled
1926 * in accordance with network preference policies.
1927 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001928 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkdc919012011-08-23 14:15:13 +02001929 List<Integer> pids = mNetRequestersPids[prevNetType];
1930 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001931 // will remove them because the net's no longer connected
1932 // need to do this now as only now do we know the pids and
1933 // can properly null things that are no longer referenced.
1934 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001935 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001936 }
1937
The Android Open Source Project28527d22009-03-03 19:31:44 -08001938 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07001939 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001940 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001941 if (info.isFailover()) {
1942 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1943 info.setFailover(false);
1944 }
1945 if (info.getReason() != null) {
1946 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1947 }
1948 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001949 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1950 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001951 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001952
Robert Greenwalt34848c02011-03-25 13:09:25 -07001953 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001954 tryFailover(prevNetType);
1955 if (mActiveDefaultNetwork != -1) {
1956 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001957 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1958 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001959 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001960 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1961 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001962 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001963 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001964
1965 // Reset interface if no other connections are using the same interface
1966 boolean doReset = true;
1967 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1968 if (linkProperties != null) {
1969 String oldIface = linkProperties.getInterfaceName();
1970 if (TextUtils.isEmpty(oldIface) == false) {
1971 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1972 if (networkStateTracker == null) continue;
1973 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1974 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1975 LinkProperties l = networkStateTracker.getLinkProperties();
1976 if (l == null) continue;
1977 if (oldIface.equals(l.getInterfaceName())) {
1978 doReset = false;
1979 break;
1980 }
1981 }
1982 }
1983 }
1984 }
1985
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001986 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001987 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001988
Jeff Sharkey971cd162011-08-29 16:02:57 -07001989 final Intent immediateIntent = new Intent(intent);
1990 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1991 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001992 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001993 /*
1994 * If the failover network is already connected, then immediately send
1995 * out a followup broadcast indicating successful failover
1996 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001997 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001998 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1999 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002000 }
2001 }
2002
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002003 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002004 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08002005 * If this is a default network, check if other defaults are available.
2006 * Try to reconnect on all available and let them hash it out when
2007 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07002008 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07002009 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002010 if (mActiveDefaultNetwork == prevNetType) {
Wink Saville89c87b92013-08-29 08:55:16 -07002011 if (DBG) {
2012 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2013 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002014 mActiveDefaultNetwork = -1;
2015 }
2016
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002017 // don't signal a reconnect for anything lower or equal priority than our
2018 // current connected default
2019 // TODO - don't filter by priority now - nice optimization but risky
2020// int currentPriority = -1;
2021// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002022// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002023// }
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002024
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002025 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07002026 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002027 if (mNetConfigs[checkType] == null) continue;
2028 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08002029 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08002030
2031// Enabling the isAvailable() optimization caused mobile to not get
2032// selected if it was in the middle of error handling. Specifically
2033// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2034// would not be available and we wouldn't get connected to anything.
2035// So removing the isAvailable() optimization below for now. TODO: This
2036// optimization should work and we need to investigate why it doesn't work.
2037// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2038// complete before it is really complete.
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002039
Wink Saville72a95b92011-01-26 15:43:49 -08002040// if (!mNetTrackers[checkType].isAvailable()) continue;
2041
Robert Greenwalt34848c02011-03-25 13:09:25 -07002042// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002043
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002044 NetworkStateTracker checkTracker = mNetTrackers[checkType];
2045 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2046 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2047 checkInfo.setFailover(true);
2048 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002049 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002050 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002051 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002052 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002053 }
2054
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002055 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002056 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07002057 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2058 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002059 }
2060
Wink Saville4f0de1e2011-08-04 15:01:58 -07002061 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002062 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2063 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002064 }
2065
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002066 private void sendInetConditionBroadcast(NetworkInfo info) {
2067 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2068 }
2069
Wink Saville4f0de1e2011-08-04 15:01:58 -07002070 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002071 if (mLockdownTracker != null) {
2072 info = mLockdownTracker.augmentNetworkInfo(info);
2073 }
2074
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002075 Intent intent = new Intent(bcastType);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002076 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002077 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002078 if (info.isFailover()) {
2079 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2080 info.setFailover(false);
2081 }
2082 if (info.getReason() != null) {
2083 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2084 }
2085 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002086 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2087 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002088 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002089 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002090 return intent;
2091 }
2092
2093 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2094 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2095 }
2096
2097 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2098 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002099 }
2100
Haoyu Baib5da5752012-06-20 14:29:57 -07002101 private void sendDataActivityBroadcast(int deviceType, boolean active) {
2102 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2103 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2104 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002105 final long ident = Binder.clearCallingIdentity();
2106 try {
2107 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2108 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2109 } finally {
2110 Binder.restoreCallingIdentity(ident);
2111 }
Haoyu Baib5da5752012-06-20 14:29:57 -07002112 }
2113
The Android Open Source Project28527d22009-03-03 19:31:44 -08002114 /**
2115 * Called when an attempt to fail over to another network has failed.
2116 * @param info the {@link NetworkInfo} for the failed network
2117 */
2118 private void handleConnectionFailure(NetworkInfo info) {
2119 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002120
Robert Greenwalt2034b912009-08-12 16:08:25 -07002121 String reason = info.getReason();
2122 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07002123
Robert Greenwalte981bc52010-10-08 16:35:52 -07002124 String reasonText;
2125 if (reason == null) {
2126 reasonText = ".";
2127 } else {
2128 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08002129 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002130 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002131
2132 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002133 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002134 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07002135 if (getActiveNetworkInfo() == null) {
2136 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2137 }
2138 if (reason != null) {
2139 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
2140 }
2141 if (extraInfo != null) {
2142 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
2143 }
2144 if (info.isFailover()) {
2145 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2146 info.setFailover(false);
2147 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002148
Robert Greenwalt34848c02011-03-25 13:09:25 -07002149 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002150 tryFailover(info.getType());
2151 if (mActiveDefaultNetwork != -1) {
2152 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002153 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2154 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002155 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002156 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2157 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002158 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002159
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002160 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002161
2162 final Intent immediateIntent = new Intent(intent);
2163 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2164 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002165 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002166 /*
2167 * If the failover network is already connected, then immediately send
2168 * out a followup broadcast indicating successful failover
2169 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002170 if (mActiveDefaultNetwork != -1) {
2171 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002172 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002173 }
2174
2175 private void sendStickyBroadcast(Intent intent) {
2176 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002177 if (!mSystemReady) {
2178 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002179 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002180 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002181 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002182 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002183 }
2184
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002185 final long ident = Binder.clearCallingIdentity();
2186 try {
2187 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2188 } finally {
2189 Binder.restoreCallingIdentity(ident);
2190 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002191 }
2192 }
2193
Wink Saville4f0de1e2011-08-04 15:01:58 -07002194 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2195 if (delayMs <= 0) {
2196 sendStickyBroadcast(intent);
2197 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002198 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002199 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2200 + intent.getAction());
2201 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002202 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2203 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2204 }
2205 }
2206
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002207 void systemReady() {
Wink Saville89c87b92013-08-29 08:55:16 -07002208 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2209 loadGlobalProxy();
2210
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002211 synchronized(this) {
2212 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002213 if (mInitialBroadcast != null) {
Dianne Hackbornbc55bd12012-08-29 18:32:08 -07002214 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002215 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002216 }
2217 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002218 // load the global proxy at startup
2219 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002220
2221 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2222 // for user to unlock device.
2223 if (!updateLockdownVpn()) {
2224 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2225 mContext.registerReceiver(mUserPresentReceiver, filter);
2226 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002227 }
2228
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002229 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2230 @Override
2231 public void onReceive(Context context, Intent intent) {
2232 // Try creating lockdown tracker, since user present usually means
2233 // unlocked keystore.
2234 if (updateLockdownVpn()) {
2235 mContext.unregisterReceiver(this);
2236 }
2237 }
2238 };
2239
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002240 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
Wink Saville89c87b92013-08-29 08:55:16 -07002241 if (((type != mNetworkPreference)
2242 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2243 || (mNetworkPreference == mActiveDefaultNetwork)) {
2244 return false;
2245 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002246 return true;
2247 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002248
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002249 private void handleConnect(NetworkInfo info) {
2250 final int newNetType = info.getType();
2251
2252 setupDataActivityTracking(newNetType);
Haoyu Bai92e03a72012-06-28 15:26:19 -07002253
The Android Open Source Project28527d22009-03-03 19:31:44 -08002254 // snapshot isFailover, because sendConnectedBroadcast() resets it
2255 boolean isFailover = info.isFailover();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002256 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002257 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002258
Wink Saville89c87b92013-08-29 08:55:16 -07002259 if (VDBG) {
2260 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2261 + " isFailover" + isFailover);
2262 }
2263
Robert Greenwalt2034b912009-08-12 16:08:25 -07002264 // if this is a default net and other default is running
2265 // kill the one not preferred
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002266 if (mNetConfigs[newNetType].isDefault()) {
2267 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2268 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002269 // tear down the other
2270 NetworkStateTracker otherNet =
2271 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002272 if (DBG) {
2273 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002274 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002275 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002276 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002277 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002278 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002279 return;
2280 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002281 } else {
2282 // don't accept this one
2283 if (VDBG) {
2284 log("Not broadcasting CONNECT_ACTION " +
2285 "to torn down network " + info.getTypeName());
2286 }
2287 teardown(thisNet);
2288 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002289 }
2290 }
2291 synchronized (ConnectivityService.this) {
2292 // have a new default network, release the transition wakelock in a second
2293 // if it's held. The second pause is to allow apps to reconnect over the
2294 // new network
2295 if (mNetTransitionWakeLock.isHeld()) {
2296 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002297 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002298 mNetTransitionWakeLockSerialNumber, 0),
2299 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002300 }
2301 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002302 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002303 // this will cause us to come up initially as unconnected and switching
2304 // to connected after our normal pause unless somebody reports us as reall
2305 // disconnected
2306 mDefaultInetConditionPublished = 0;
2307 mDefaultConnectionSequence++;
2308 mInetConditionChangeInFlight = false;
2309 // Don't do this - if we never sign in stay, grey
2310 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002311 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002312 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002313 updateNetworkSettings(thisNet);
sy.yun30043282013-09-02 05:24:09 +09002314 updateMtuSizeSettings(thisNet);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002315 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002316 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002317
2318 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002319 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002320 try {
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002321 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002322 } catch (RemoteException e) {
2323 // ignored; service lives in system_server
2324 }
2325 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002326 }
2327
Wink Savilleffdadd62013-08-07 16:22:47 -07002328 /** @hide */
2329 @Override
2330 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2331 enforceConnectivityInternalPermission();
2332 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2333 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2334 }
2335
The Android Open Source Project28527d22009-03-03 19:31:44 -08002336 /**
Haoyu Bai92e03a72012-06-28 15:26:19 -07002337 * Setup data activity tracking for the given network interface.
2338 *
2339 * Every {@code setupDataActivityTracking} should be paired with a
2340 * {@link removeDataActivityTracking} for cleanup.
2341 */
2342 private void setupDataActivityTracking(int type) {
2343 final NetworkStateTracker thisNet = mNetTrackers[type];
2344 final String iface = thisNet.getLinkProperties().getInterfaceName();
2345
2346 final int timeout;
2347
2348 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brown87272712012-09-25 15:03:20 -07002349 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2350 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002351 0);
2352 // Canonicalize mobile network type
2353 type = ConnectivityManager.TYPE_MOBILE;
2354 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brown87272712012-09-25 15:03:20 -07002355 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2356 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002357 0);
2358 } else {
2359 // do not track any other networks
2360 timeout = 0;
2361 }
2362
2363 if (timeout > 0 && iface != null) {
2364 try {
2365 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2366 } catch (RemoteException e) {
2367 }
2368 }
2369 }
2370
2371 /**
2372 * Remove data activity tracking when network disconnects.
2373 */
2374 private void removeDataActivityTracking(int type) {
2375 final NetworkStateTracker net = mNetTrackers[type];
2376 final String iface = net.getLinkProperties().getInterfaceName();
2377
2378 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2379 ConnectivityManager.TYPE_WIFI == type)) {
2380 try {
2381 // the call fails silently if no idletimer setup for this interface
2382 mNetd.removeIdleTimer(iface);
2383 } catch (RemoteException e) {
2384 }
2385 }
2386 }
2387
2388 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002389 * After a change in the connectivity state of a network. We're mainly
2390 * concerned with making sure that the list of DNS servers is set up
2391 * according to which networks are connected, and ensuring that the
2392 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002393 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002394 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002395 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
Chad Brubaker78850f32013-07-15 16:34:04 -07002396 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
Wink Saville89c87b92013-08-29 08:55:16 -07002397 if (VDBG) {
2398 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2399 + " resetMask=" + resetMask);
2400 }
Wink Saville051a6642011-07-13 13:44:13 -07002401
The Android Open Source Project28527d22009-03-03 19:31:44 -08002402 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002403 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002404 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002405 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002406 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002407
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002408 LinkProperties curLp = mCurrentLinkProperties[netType];
2409 LinkProperties newLp = null;
2410
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002411 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002412 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002413 if (VDBG) {
2414 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2415 " doReset=" + doReset + " resetMask=" + resetMask +
2416 "\n curLp=" + curLp +
2417 "\n newLp=" + newLp);
2418 }
2419
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002420 if (curLp != null) {
2421 if (curLp.isIdenticalInterfaceName(newLp)) {
2422 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2423 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2424 for (LinkAddress linkAddr : car.removed) {
2425 if (linkAddr.getAddress() instanceof Inet4Address) {
2426 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2427 }
2428 if (linkAddr.getAddress() instanceof Inet6Address) {
2429 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2430 }
Wink Saville051a6642011-07-13 13:44:13 -07002431 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002432 if (DBG) {
2433 log("handleConnectivityChange: addresses changed" +
2434 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2435 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002436 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002437 } else {
2438 if (DBG) {
2439 log("handleConnectivityChange: address are the same reset per doReset" +
2440 " linkProperty[" + netType + "]:" +
2441 " resetMask=" + resetMask);
2442 }
Wink Saville051a6642011-07-13 13:44:13 -07002443 }
2444 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002445 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002446 if (DBG) {
2447 log("handleConnectivityChange: interface not not equivalent reset both" +
2448 " linkProperty[" + netType + "]:" +
2449 " resetMask=" + resetMask);
2450 }
Wink Saville051a6642011-07-13 13:44:13 -07002451 }
Wink Saville051a6642011-07-13 13:44:13 -07002452 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002453 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002454 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002455 }
2456 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002457 if (VDBG) {
2458 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2459 " doReset=" + doReset + " resetMask=" + resetMask +
2460 "\n curLp=" + curLp +
2461 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002462 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002463 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002464 mCurrentLinkProperties[netType] = newLp;
Chad Brubaker78850f32013-07-15 16:34:04 -07002465 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002466
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002467 if (resetMask != 0 || resetDns) {
Wink Saville89c87b92013-08-29 08:55:16 -07002468 if (VDBG) log("handleConnectivityChange: resetting");
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002469 if (curLp != null) {
Wink Saville89c87b92013-08-29 08:55:16 -07002470 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002471 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002472 if (TextUtils.isEmpty(iface) == false) {
2473 if (resetMask != 0) {
2474 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2475 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002476
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002477 // Tell VPN the interface is down. It is a temporary
2478 // but effective fix to make VPN aware of the change.
2479 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07002480 synchronized(mVpns) {
2481 for (int i = 0; i < mVpns.size(); i++) {
2482 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2483 }
2484 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002485 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002486 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002487 if (resetDns) {
2488 flushVmDnsCache();
2489 if (VDBG) log("resetting DNS cache for " + iface);
2490 try {
2491 mNetd.flushInterfaceDnsCache(iface);
2492 } catch (Exception e) {
2493 // never crash - catch them all
2494 if (DBG) loge("Exception resetting dns cache: " + e);
2495 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002496 }
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002497 } else {
2498 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002499 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002500 }
2501 }
2502 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002503
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002504 // Update 464xlat state.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002505 NetworkStateTracker tracker = mNetTrackers[netType];
2506 if (mClat.requiresClat(netType, tracker)) {
Wink Saville89c87b92013-08-29 08:55:16 -07002507
Lorenzo Colitti7e5624b2013-03-28 14:13:43 +09002508 // If the connection was previously using clat, but is not using it now, stop the clat
2509 // daemon. Normally, this happens automatically when the connection disconnects, but if
2510 // the disconnect is not reported, or if the connection's LinkProperties changed for
2511 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2512 // still be running. If it's not running, then stopping it is a no-op.
2513 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2514 mClat.stopClat();
2515 }
2516 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002517 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2518 mClat.startClat(tracker);
2519 } else {
2520 mClat.stopClat();
2521 }
2522 }
2523
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002524 // TODO: Temporary notifying upstread change to Tethering.
2525 // @see bug/4455071
2526 /** Notify TetheringService if interface name has been changed. */
2527 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002528 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002529 if (isTetheringSupported()) {
2530 mTethering.handleTetherIfaceChange();
2531 }
2532 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002533 }
2534
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002535 /**
2536 * Add and remove routes using the old properties (null if not previously connected),
2537 * new properties (null if becoming disconnected). May even be double null, which
2538 * is a noop.
2539 * Uses isLinkDefault to determine if default routes should be set or conversely if
2540 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002541 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002542 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002543 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
Chad Brubaker78850f32013-07-15 16:34:04 -07002544 boolean isLinkDefault, boolean exempt) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002545 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002546 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2547 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002548 if (curLp != null) {
2549 // check for the delta between the current set and the new
Lorenzo Colitti43553b62013-07-31 23:23:21 +09002550 routeDiff = curLp.compareAllRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002551 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002552 } else if (newLp != null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002553 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002554 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002555 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002556
Robert Greenwalt8d777252011-08-15 12:31:55 -07002557 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2558
Robert Greenwalt98107422011-07-22 11:55:33 -07002559 for (RouteInfo r : routeDiff.removed) {
2560 if (isLinkDefault || ! r.isDefaultRoute()) {
Wink Saville89c87b92013-08-29 08:55:16 -07002561 if (VDBG) log("updateRoutes: default remove route r=" + r);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002562 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2563 }
2564 if (isLinkDefault == false) {
2565 // remove from a secondary route table
2566 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002567 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002568 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002569
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002570 if (!isLinkDefault) {
2571 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002572 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002573 // routes changed - remove all old dns entries and add new
2574 if (curLp != null) {
2575 for (InetAddress oldDns : curLp.getDnses()) {
2576 removeRouteToAddress(curLp, oldDns);
2577 }
2578 }
2579 if (newLp != null) {
2580 for (InetAddress newDns : newLp.getDnses()) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002581 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt98107422011-07-22 11:55:33 -07002582 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002583 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002584 } else {
2585 // no change in routes, check for change in dns themselves
2586 for (InetAddress oldDns : dnsDiff.removed) {
2587 removeRouteToAddress(curLp, oldDns);
2588 }
2589 for (InetAddress newDns : dnsDiff.added) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002590 addRouteToAddress(newLp, newDns, exempt);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002591 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002592 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002593 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002594
2595 for (RouteInfo r : routeDiff.added) {
2596 if (isLinkDefault || ! r.isDefaultRoute()) {
Chad Brubaker78850f32013-07-15 16:34:04 -07002597 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
Robert Greenwalt921bf382013-04-05 16:49:32 -07002598 } else {
2599 // add to a secondary route table
Chad Brubaker78850f32013-07-15 16:34:04 -07002600 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
Robert Greenwalt921bf382013-04-05 16:49:32 -07002601
2602 // many radios add a default route even when we don't want one.
2603 // remove the default route unless somebody else has asked for it
2604 String ifaceName = newLp.getInterfaceName();
Chad Brubaker78850f32013-07-15 16:34:04 -07002605 synchronized (mRoutesLock) {
2606 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2607 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2608 try {
2609 mNetd.removeRoute(ifaceName, r);
2610 } catch (Exception e) {
2611 // never crash - catch them all
2612 if (DBG) loge("Exception trying to remove a route: " + e);
2613 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002614 }
2615 }
2616 }
2617 }
2618
Robert Greenwalt8d777252011-08-15 12:31:55 -07002619 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002620 }
2621
sy.yun30043282013-09-02 05:24:09 +09002622 /**
2623 * Reads the network specific MTU size from reources.
2624 * and set it on it's iface.
2625 */
2626 private void updateMtuSizeSettings(NetworkStateTracker nt) {
2627 final String iface = nt.getLinkProperties().getInterfaceName();
2628 final int mtu = nt.getLinkProperties().getMtu();
2629
2630 if (mtu < 68 || mtu > 10000) {
2631 loge("Unexpected mtu value: " + nt);
2632 return;
2633 }
2634
2635 try {
2636 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2637 mNetd.setMtu(iface, mtu);
2638 } catch (Exception e) {
2639 Slog.e(TAG, "exception in setMtu()" + e);
2640 }
2641 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002642
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002643 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002644 * Reads the network specific TCP buffer sizes from SystemProperties
2645 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2646 * wide use
2647 */
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002648 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002649 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002650 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002651
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002652 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002653 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002654
2655 // Setting to default values so we won't be stuck to previous values
2656 key = "net.tcp.buffersize.default";
2657 bufferSizes = SystemProperties.get(key);
2658 }
2659
2660 // Set values in kernel
2661 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002662 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002663 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002664 + "] which comes from [" + key + "]");
2665 }
2666 setBufferSize(bufferSizes);
2667 }
2668 }
2669
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07002670 /**
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002671 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2672 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2673 *
2674 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2675 * writeMin, writeInitial, writeMax"
2676 */
2677 private void setBufferSize(String bufferSizes) {
2678 try {
2679 String[] values = bufferSizes.split(",");
2680
2681 if (values.length == 6) {
2682 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002683 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2684 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2685 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2686 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2687 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2688 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002689 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002690 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002691 }
2692 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002693 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002694 }
2695 }
2696
Robert Greenwalt2034b912009-08-12 16:08:25 -07002697 /**
2698 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2699 * on the highest priority active net which this process requested.
2700 * If there aren't any, clear it out
2701 */
Mattias Falkdc919012011-08-23 14:15:13 +02002702 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002703 {
Mattias Falkdc919012011-08-23 14:15:13 +02002704 if (VDBG) log("reassessPidDns for pid " + pid);
2705 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002706 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002707 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002708 continue;
2709 }
2710 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002711 if (nt.getNetworkInfo().isConnected() &&
2712 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002713 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002714 if (p == null) continue;
Mattias Falkdc919012011-08-23 14:15:13 +02002715 if (mNetRequestersPids[i].contains(myPid)) {
2716 try {
2717 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2718 } catch (Exception e) {
2719 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002720 }
Mattias Falkdc919012011-08-23 14:15:13 +02002721 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002722 }
2723 }
2724 }
2725 // nothing found - delete
Mattias Falkdc919012011-08-23 14:15:13 +02002726 try {
2727 mNetd.clearDnsInterfaceForPid(pid);
2728 } catch (Exception e) {
2729 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002730 }
2731 }
2732
Mattias Falkdc919012011-08-23 14:15:13 +02002733 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002734 /*
2735 * Tell the VMs to toss their DNS caches
2736 */
2737 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2738 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002739 /*
2740 * Connectivity events can happen before boot has completed ...
2741 */
2742 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002743 final long ident = Binder.clearCallingIdentity();
2744 try {
2745 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2746 } finally {
2747 Binder.restoreCallingIdentity(ident);
2748 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002749 }
2750
Chia-chi Yehcc844502011-07-14 18:01:57 -07002751 // Caller must grab mDnsLock.
Mattias Falkdc919012011-08-23 14:15:13 +02002752 private void updateDnsLocked(String network, String iface,
Chad Brubaker45e721f2013-07-23 17:13:36 -07002753 Collection<InetAddress> dnses, String domains, boolean defaultDns) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002754 int last = 0;
2755 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkdc919012011-08-23 14:15:13 +02002756 dnses = new ArrayList();
2757 dnses.add(mDefaultDns);
2758 if (DBG) {
2759 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002760 }
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002761 }
2762
Mattias Falkdc919012011-08-23 14:15:13 +02002763 try {
2764 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Chad Brubaker45e721f2013-07-23 17:13:36 -07002765 if (defaultDns) {
2766 mNetd.setDefaultInterfaceForDns(iface);
2767 }
2768
Robert Greenwaltd44340d2013-02-11 15:25:10 -08002769 for (InetAddress dns : dnses) {
2770 ++last;
2771 String key = "net.dns" + last;
2772 String value = dns.getHostAddress();
2773 SystemProperties.set(key, value);
2774 }
2775 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2776 String key = "net.dns" + i;
2777 SystemProperties.set(key, "");
2778 }
2779 mNumDnsEntries = last;
Mattias Falkdc919012011-08-23 14:15:13 +02002780 } catch (Exception e) {
Robert Greenwalt68534c82013-09-24 11:05:57 -07002781 loge("exception setting default dns interface: " + e);
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002782 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002783 }
2784
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002785 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002786 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002787 NetworkStateTracker nt = mNetTrackers[netType];
2788 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002789 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002790 if (p == null) return;
2791 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002792 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002793 String network = nt.getNetworkInfo().getTypeName();
2794 synchronized (mDnsLock) {
Chad Brubakera8e81122013-07-23 17:44:41 -07002795 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002796 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002797 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002798 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002799 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt0bc6c962012-11-09 10:52:27 -08002800 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002801 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002802 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002803 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002804 // set per-pid dns for attached secondary nets
Mattias Falkdc919012011-08-23 14:15:13 +02002805 List<Integer> pids = mNetRequestersPids[netType];
2806 for (Integer pid : pids) {
2807 try {
2808 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2809 } catch (Exception e) {
2810 Slog.e(TAG, "exception setting interface for pid: " + e);
2811 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002812 }
2813 }
Mattias Falkdc919012011-08-23 14:15:13 +02002814 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002815 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002816 }
2817
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002818 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002819 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2820 NETWORK_RESTORE_DELAY_PROP_NAME);
2821 if(restoreDefaultNetworkDelayStr != null &&
2822 restoreDefaultNetworkDelayStr.length() != 0) {
2823 try {
2824 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2825 } catch (NumberFormatException e) {
2826 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002827 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002828 // if the system property isn't set, use the value for the apn type
2829 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2830
2831 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2832 (mNetConfigs[networkType] != null)) {
2833 ret = mNetConfigs[networkType].restoreTime;
2834 }
2835 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002836 }
2837
2838 @Override
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002839 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2840 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002841 if (mContext.checkCallingOrSelfPermission(
2842 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002843 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002844 pw.println("Permission Denial: can't dump ConnectivityService " +
2845 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2846 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002847 return;
2848 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002849
2850 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002851 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002852 for (int i = 0; i < mNetTrackers.length; i++) {
2853 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002854 if (nst != null) {
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002855 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2856 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002857 if (nst.getNetworkInfo().isConnected()) {
2858 pw.println("Active network: " + nst.getNetworkInfo().
2859 getTypeName());
2860 }
2861 pw.println(nst.getNetworkInfo());
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002862 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002863 pw.println(nst);
2864 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002865 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002866 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002867 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002868
2869 pw.println("Network Requester Pids:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002870 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002871 for (int net : mPriorityList) {
2872 String pidString = net + ": ";
Mattias Falkdc919012011-08-23 14:15:13 +02002873 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002874 pidString = pidString + pid.toString() + ", ";
2875 }
2876 pw.println(pidString);
2877 }
2878 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002879 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002880
2881 pw.println("FeatureUsers:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002882 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002883 for (Object requester : mFeatureUsers) {
2884 pw.println(requester.toString());
2885 }
2886 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002887 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002888
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002889 synchronized (this) {
2890 pw.println("NetworkTranstionWakeLock is currently " +
2891 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2892 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2893 }
2894 pw.println();
2895
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002896 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002897
2898 if (mInetLog != null) {
2899 pw.println();
2900 pw.println("Inet condition reports:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002901 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002902 for(int i = 0; i < mInetLog.size(); i++) {
2903 pw.println(mInetLog.get(i));
2904 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002905 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002906 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002907 }
2908
Robert Greenwalt2034b912009-08-12 16:08:25 -07002909 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002910 private class NetworkStateTrackerHandler extends Handler {
2911 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002912 super(looper);
2913 }
2914
The Android Open Source Project28527d22009-03-03 19:31:44 -08002915 @Override
2916 public void handleMessage(Message msg) {
2917 NetworkInfo info;
2918 switch (msg.what) {
Wink Saville89c87b92013-08-29 08:55:16 -07002919 case NetworkStateTracker.EVENT_STATE_CHANGED: {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002920 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002921 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002922
Wink Savillea7d56572011-09-21 11:05:43 -07002923 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
Wink Saville860f5282013-09-05 12:02:25 -07002924 (state == NetworkInfo.State.DISCONNECTED) ||
2925 (state == NetworkInfo.State.SUSPENDED)) {
Wink Savillea7d56572011-09-21 11:05:43 -07002926 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002927 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002928 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002929 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002930
Wink Saville89c87b92013-08-29 08:55:16 -07002931 // Since mobile has the notion of a network/apn that can be used for
2932 // provisioning we need to check every time we're connected as
2933 // CaptiveProtalTracker won't detected it because DCT doesn't report it
2934 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
2935 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
2936 // is received by MDST and sent here as EVENT_STATE_CHANGED.
2937 if (ConnectivityManager.isNetworkTypeMobile(info.getType())
Wink Saville9564f2b2013-07-16 17:16:37 -07002938 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2939 Settings.Global.DEVICE_PROVISIONED, 0))
Wink Savilleab773a72013-09-14 09:04:53 -07002940 && (((state == NetworkInfo.State.CONNECTED)
2941 && (info.getType() == ConnectivityManager.TYPE_MOBILE))
2942 || info.isConnectedToProvisioningNetwork())) {
2943 log("ConnectivityChange checkMobileProvisioning for"
2944 + " TYPE_MOBILE or ProvisioningNetwork");
Wink Saville89c87b92013-08-29 08:55:16 -07002945 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
Wink Saville9564f2b2013-07-16 17:16:37 -07002946 }
2947
Jeff Sharkeybde32692012-11-09 15:57:02 -08002948 EventLogTags.writeConnectivityStateChanged(
2949 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002950
2951 if (info.getDetailedState() ==
2952 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002953 handleConnectionFailure(info);
Wink Saville860f5282013-09-05 12:02:25 -07002954 } else if (info.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -07002955 /**
2956 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
2957 * for now its an in between network, its a network that
2958 * is actually a default network but we don't want it to be
2959 * announced as such to keep background applications from
2960 * trying to use it. It turns out that some still try so we
2961 * take the additional step of clearing any default routes
2962 * to the link that may have incorrectly setup by the lower
2963 * levels.
2964 */
2965 LinkProperties lp = getLinkProperties(info.getType());
2966 if (DBG) {
2967 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
2968 }
2969
2970 // Clear any default routes setup by the radio so
2971 // any activity by applications trying to use this
2972 // connection will fail until the provisioning network
2973 // is enabled.
2974 for (RouteInfo r : lp.getRoutes()) {
2975 removeRoute(lp, r, TO_DEFAULT_TABLE);
2976 }
Robert Greenwalt12c44552009-12-07 11:33:18 -08002977 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002978 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002979 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002980 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002981 // the logic here is, handle SUSPENDED the same as
2982 // DISCONNECTED. The only difference being we are
2983 // broadcasting an intent with NetworkInfo that's
2984 // suspended. This allows the applications an
2985 // opportunity to handle DISCONNECTED and SUSPENDED
2986 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002987 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002988 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002989 handleConnect(info);
2990 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002991 if (mLockdownTracker != null) {
2992 mLockdownTracker.onNetworkInfoChanged(info);
2993 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002994 break;
Wink Saville89c87b92013-08-29 08:55:16 -07002995 }
2996 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002997 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002998 // TODO: Temporary allowing network configuration
2999 // change not resetting sockets.
3000 // @see bug/4455071
3001 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003002 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003003 }
3004 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07003005 info = (NetworkInfo) msg.obj;
Wink Saville89c87b92013-08-29 08:55:16 -07003006 int type = info.getType();
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07003007 updateNetworkSettings(mNetTrackers[type]);
3008 break;
Wink Saville89c87b92013-08-29 08:55:16 -07003009 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003010 }
3011 }
3012 }
3013
3014 private class InternalHandler extends Handler {
3015 public InternalHandler(Looper looper) {
3016 super(looper);
3017 }
3018
3019 @Override
3020 public void handleMessage(Message msg) {
3021 NetworkInfo info;
3022 switch (msg.what) {
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003023 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003024 String causedBy = null;
3025 synchronized (ConnectivityService.this) {
3026 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3027 mNetTransitionWakeLock.isHeld()) {
3028 mNetTransitionWakeLock.release();
3029 causedBy = mNetTransitionWakeLockCausedBy;
3030 }
3031 }
3032 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003033 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003034 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07003035 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003036 }
3037 case EVENT_RESTORE_DEFAULT_NETWORK: {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003038 FeatureUser u = (FeatureUser)msg.obj;
3039 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07003040 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003041 }
3042 case EVENT_INET_CONDITION_CHANGE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003043 int netType = msg.arg1;
3044 int condition = msg.arg2;
3045 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003046 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003047 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003048 case EVENT_INET_CONDITION_HOLD_END: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003049 int netType = msg.arg1;
3050 int sequence = msg.arg2;
Wink Saville3e866722013-01-31 00:30:13 +00003051 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07003052 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003053 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003054 case EVENT_SET_NETWORK_PREFERENCE: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003055 int preference = msg.arg1;
3056 handleSetNetworkPreference(preference);
3057 break;
3058 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003059 case EVENT_SET_MOBILE_DATA: {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003060 boolean enabled = (msg.arg1 == ENABLED);
3061 handleSetMobileData(enabled);
3062 break;
3063 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003064 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003065 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07003066 break;
3067 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003068 case EVENT_SET_DEPENDENCY_MET: {
Robert Greenwalt34848c02011-03-25 13:09:25 -07003069 boolean met = (msg.arg1 == ENABLED);
3070 handleSetDependencyMet(msg.arg2, met);
3071 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003072 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003073 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville4f0de1e2011-08-04 15:01:58 -07003074 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07003075 sendStickyBroadcast(intent);
3076 break;
3077 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07003078 case EVENT_SET_POLICY_DATA_ENABLE: {
3079 final int networkType = msg.arg1;
3080 final boolean enabled = msg.arg2 == ENABLED;
3081 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003082 break;
3083 }
3084 case EVENT_VPN_STATE_CHANGED: {
3085 if (mLockdownTracker != null) {
3086 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3087 }
3088 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07003089 }
Wink Saville690cb182013-06-29 21:10:57 -07003090 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3091 int tag = mEnableFailFastMobileDataTag.get();
3092 if (msg.arg1 == tag) {
3093 MobileDataStateTracker mobileDst =
3094 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3095 if (mobileDst != null) {
3096 mobileDst.setEnableFailFastMobileData(msg.arg2);
3097 }
3098 } else {
3099 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3100 + " != tag:" + tag);
3101 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003102 break;
Wink Saville690cb182013-06-29 21:10:57 -07003103 }
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003104 case EVENT_SAMPLE_INTERVAL_ELAPSED: {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07003105 handleNetworkSamplingTimeout();
3106 break;
Sreeram Ramachandran2103b572013-08-27 11:41:19 -07003107 }
Jason Monk445cea82013-10-10 14:02:51 -04003108 case EVENT_PROXY_HAS_CHANGED: {
3109 handleApplyDefaultProxy((ProxyProperties)msg.obj);
3110 break;
3111 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003112 }
3113 }
3114 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003115
3116 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003117 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003118 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003119
3120 if (isTetheringSupported()) {
3121 return mTethering.tether(iface);
3122 } else {
3123 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3124 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003125 }
3126
3127 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003128 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003129 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003130
3131 if (isTetheringSupported()) {
3132 return mTethering.untether(iface);
3133 } else {
3134 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3135 }
3136 }
3137
3138 // javadoc from interface
3139 public int getLastTetherError(String iface) {
3140 enforceTetherAccessPermission();
3141
3142 if (isTetheringSupported()) {
3143 return mTethering.getLastTetherError(iface);
3144 } else {
3145 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3146 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003147 }
3148
3149 // TODO - proper iface API for selection by property, inspection, etc
3150 public String[] getTetherableUsbRegexs() {
3151 enforceTetherAccessPermission();
3152 if (isTetheringSupported()) {
3153 return mTethering.getTetherableUsbRegexs();
3154 } else {
3155 return new String[0];
3156 }
3157 }
3158
3159 public String[] getTetherableWifiRegexs() {
3160 enforceTetherAccessPermission();
3161 if (isTetheringSupported()) {
3162 return mTethering.getTetherableWifiRegexs();
3163 } else {
3164 return new String[0];
3165 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003166 }
3167
Danica Chang96567052010-08-11 14:54:43 -07003168 public String[] getTetherableBluetoothRegexs() {
3169 enforceTetherAccessPermission();
3170 if (isTetheringSupported()) {
3171 return mTethering.getTetherableBluetoothRegexs();
3172 } else {
3173 return new String[0];
3174 }
3175 }
3176
Mike Lockwooded4a1742011-07-19 13:04:47 -07003177 public int setUsbTethering(boolean enable) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08003178 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07003179 if (isTetheringSupported()) {
3180 return mTethering.setUsbTethering(enable);
3181 } else {
3182 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3183 }
3184 }
3185
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003186 // TODO - move iface listing, queries, etc to new module
3187 // javadoc from interface
3188 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003189 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003190 return mTethering.getTetherableIfaces();
3191 }
3192
3193 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003194 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08003195 return mTethering.getTetheredIfaces();
3196 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003197
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003198 public String[] getTetheringErroredIfaces() {
3199 enforceTetherAccessPermission();
3200 return mTethering.getErroredIfaces();
3201 }
3202
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003203 // if ro.tether.denied = true we default to no tethering
3204 // gservices could set the secure setting to 1 though to enable it on a build where it
3205 // had previously been turned off.
3206 public boolean isTetheringSupported() {
3207 enforceTetherAccessPermission();
3208 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brown87272712012-09-25 15:03:20 -07003209 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3210 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt81b02742013-07-18 14:24:42 -07003211 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3212 mTethering.getTetherableWifiRegexs().length != 0 ||
3213 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3214 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003215 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003216
3217 // An API NetworkStateTrackers can call when they lose their network.
3218 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3219 // whichever happens first. The timer is started by the first caller and not
3220 // restarted by subsequent callers.
3221 public void requestNetworkTransitionWakelock(String forWhom) {
3222 enforceConnectivityInternalPermission();
3223 synchronized (this) {
3224 if (mNetTransitionWakeLock.isHeld()) return;
3225 mNetTransitionWakeLockSerialNumber++;
3226 mNetTransitionWakeLock.acquire();
3227 mNetTransitionWakeLockCausedBy = forWhom;
3228 }
3229 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003230 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003231 mNetTransitionWakeLockSerialNumber, 0),
3232 mNetTransitionWakeLockTimeout);
3233 return;
3234 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003235
Robert Greenwalt986c7412010-09-08 15:24:47 -07003236 // 100 percent is full good, 0 is full bad.
3237 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003238 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003239 mContext.enforceCallingOrSelfPermission(
3240 android.Manifest.permission.STATUS_BAR,
3241 "ConnectivityService");
3242
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003243 if (DBG) {
3244 int pid = getCallingPid();
3245 int uid = getCallingUid();
3246 String s = pid + "(" + uid + ") reports inet is " +
3247 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3248 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3249 mInetLog.add(s);
3250 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3251 mInetLog.remove(0);
3252 }
3253 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003254 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003255 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3256 }
3257
3258 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003259 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003260 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003261 return;
3262 }
3263 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003264 if (DBG) log("handleInetConditionChange: net=" + netType +
3265 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003266 return;
3267 }
Wink Savillea7d56572011-09-21 11:05:43 -07003268 if (VDBG) {
3269 log("handleInetConditionChange: net=" +
3270 netType + ", condition=" + condition +
Wink Saville3e866722013-01-31 00:30:13 +00003271 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003272 }
Wink Saville3e866722013-01-31 00:30:13 +00003273 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003274 int delay;
3275 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003276 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003277 // setup a new hold to debounce this
Wink Saville3e866722013-01-31 00:30:13 +00003278 if (mDefaultInetCondition > 50) {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003279 delay = Settings.Global.getInt(mContext.getContentResolver(),
3280 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003281 } else {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003282 delay = Settings.Global.getInt(mContext.getContentResolver(),
3283 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003284 }
3285 mInetConditionChangeInFlight = true;
3286 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville3e866722013-01-31 00:30:13 +00003287 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003288 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003289 // we've set the new condition, when this hold ends that will get picked up
3290 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003291 }
3292 }
3293
Wink Saville3e866722013-01-31 00:30:13 +00003294 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003295 if (DBG) {
Wink Saville3e866722013-01-31 00:30:13 +00003296 log("handleInetConditionHoldEnd: net=" + netType +
3297 ", condition=" + mDefaultInetCondition +
3298 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003299 }
3300 mInetConditionChangeInFlight = false;
3301
3302 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003303 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003304 return;
3305 }
3306 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003307 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003308 return;
3309 }
Wink Saville3e866722013-01-31 00:30:13 +00003310 // TODO: Figure out why this optimization sometimes causes a
3311 // change in mDefaultInetCondition to be missed and the
3312 // UI to not be updated.
3313 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3314 // if (DBG) log("no change in condition - aborting");
3315 // return;
3316 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003317 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3318 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003319 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003320 return;
3321 }
Wink Saville3e866722013-01-31 00:30:13 +00003322 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003323 sendInetConditionBroadcast(networkInfo);
3324 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003325 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003326
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003327 public ProxyProperties getProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003328 // this information is already available as a world read/writable jvm property
3329 // so this API change wouldn't have a benifit. It also breaks the passing
3330 // of proxy info to all the JVMs.
3331 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003332 synchronized (mProxyLock) {
Jason Monk43324ee2013-07-03 17:04:33 -04003333 ProxyProperties ret = mGlobalProxy;
3334 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3335 return ret;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003336 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003337 }
3338
3339 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003340 enforceConnectivityInternalPermission();
Jason Monk43324ee2013-07-03 17:04:33 -04003341
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003342 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003343 if (proxyProperties == mGlobalProxy) return;
3344 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3345 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3346
3347 String host = "";
3348 int port = 0;
3349 String exclList = "";
Jason Monk43324ee2013-07-03 17:04:33 -04003350 String pacFileUrl = "";
3351 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3352 !TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi08e512b2013-11-11 13:52:58 -08003353 if (!proxyProperties.isValid()) {
3354 if (DBG)
3355 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3356 return;
3357 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003358 mGlobalProxy = new ProxyProperties(proxyProperties);
3359 host = mGlobalProxy.getHost();
3360 port = mGlobalProxy.getPort();
3361 exclList = mGlobalProxy.getExclusionList();
Jason Monk43324ee2013-07-03 17:04:33 -04003362 if (proxyProperties.getPacFileUrl() != null) {
3363 pacFileUrl = proxyProperties.getPacFileUrl();
3364 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003365 } else {
3366 mGlobalProxy = null;
3367 }
3368 ContentResolver res = mContext.getContentResolver();
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003369 final long token = Binder.clearCallingIdentity();
3370 try {
3371 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3372 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3373 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3374 exclList);
Jason Monk43324ee2013-07-03 17:04:33 -04003375 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003376 } finally {
3377 Binder.restoreCallingIdentity(token);
3378 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003379 }
3380
3381 if (mGlobalProxy == null) {
3382 proxyProperties = mDefaultProxy;
3383 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003384 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003385 }
3386
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003387 private void loadGlobalProxy() {
3388 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003389 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3390 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3391 String exclList = Settings.Global.getString(res,
3392 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk43324ee2013-07-03 17:04:33 -04003393 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3394 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3395 ProxyProperties proxyProperties;
3396 if (!TextUtils.isEmpty(pacFileUrl)) {
3397 proxyProperties = new ProxyProperties(pacFileUrl);
3398 } else {
3399 proxyProperties = new ProxyProperties(host, port, exclList);
3400 }
Raj Mamadgi08e512b2013-11-11 13:52:58 -08003401 if (!proxyProperties.isValid()) {
3402 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3403 return;
3404 }
3405
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003406 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003407 mGlobalProxy = proxyProperties;
3408 }
3409 }
3410 }
3411
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003412 public ProxyProperties getGlobalProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003413 // this information is already available as a world read/writable jvm property
3414 // so this API change wouldn't have a benifit. It also breaks the passing
3415 // of proxy info to all the JVMs.
3416 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003417 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003418 return mGlobalProxy;
3419 }
3420 }
3421
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003422 private void handleApplyDefaultProxy(ProxyProperties proxy) {
Jason Monk43324ee2013-07-03 17:04:33 -04003423 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3424 && TextUtils.isEmpty(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003425 proxy = null;
3426 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003427 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003428 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003429 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwaltcf8c8942013-11-18 09:43:59 -08003430 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi08e512b2013-11-11 13:52:58 -08003431 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3432 return;
3433 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003434 mDefaultProxy = proxy;
3435
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003436 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003437 if (!mDefaultProxyDisabled) {
3438 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003439 }
3440 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003441 }
3442
3443 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003444 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3445 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003446 if (!TextUtils.isEmpty(proxy)) {
3447 String data[] = proxy.split(":");
Andreas Huber9df89552013-05-28 15:17:37 -07003448 if (data.length == 0) {
3449 return;
3450 }
3451
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003452 String proxyHost = data[0];
3453 int proxyPort = 8080;
3454 if (data.length > 1) {
3455 try {
3456 proxyPort = Integer.parseInt(data[1]);
3457 } catch (NumberFormatException e) {
3458 return;
3459 }
3460 }
3461 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3462 setGlobalProxy(p);
3463 }
3464 }
3465
3466 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003467 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Jason Monkaf9ded02013-08-23 19:21:25 -04003468 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt78f28112011-08-02 17:18:41 -07003469 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003470 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003471 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3472 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003473 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07003474 final long ident = Binder.clearCallingIdentity();
3475 try {
3476 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3477 } finally {
3478 Binder.restoreCallingIdentity(ident);
3479 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003480 }
3481
3482 private static class SettingsObserver extends ContentObserver {
3483 private int mWhat;
3484 private Handler mHandler;
3485 SettingsObserver(Handler handler, int what) {
3486 super(handler);
3487 mHandler = handler;
3488 mWhat = what;
3489 }
3490
3491 void observe(Context context) {
3492 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003493 resolver.registerContentObserver(Settings.Global.getUriFor(
3494 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003495 }
3496
3497 @Override
3498 public void onChange(boolean selfChange) {
3499 mHandler.obtainMessage(mWhat).sendToTarget();
3500 }
3501 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003502
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003503 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003504 Slog.d(TAG, s);
3505 }
3506
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003507 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003508 Slog.e(TAG, s);
3509 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003510
repo syncf5de5572011-07-29 23:55:49 -07003511 int convertFeatureToNetworkType(int networkType, String feature) {
3512 int usedNetworkType = networkType;
3513
3514 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3515 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3516 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3517 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3518 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3519 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3520 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3521 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3522 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3523 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3524 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3525 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3526 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3527 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3528 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3529 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3530 } else {
3531 Slog.e(TAG, "Can't match any mobile netTracker!");
3532 }
3533 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3534 if (TextUtils.equals(feature, "p2p")) {
3535 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3536 } else {
3537 Slog.e(TAG, "Can't match any wifi netTracker!");
3538 }
3539 } else {
3540 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003541 }
repo syncf5de5572011-07-29 23:55:49 -07003542 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003543 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003544
3545 private static <T> T checkNotNull(T value, String message) {
3546 if (value == null) {
3547 throw new NullPointerException(message);
3548 }
3549 return value;
3550 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003551
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003552 /**
3553 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003554 * VpnBuilder and not available in ConnectivityManager. Permissions
3555 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003556 * @hide
3557 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003558 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003559 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003560 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003561 try {
3562 int type = mActiveDefaultNetwork;
Chad Brubakerccae0d32013-06-14 11:16:51 -07003563 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003564 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003565 synchronized(mVpns) {
3566 mVpns.get(user).protect(socket,
3567 mNetTrackers[type].getLinkProperties().getInterfaceName());
3568 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003569 return true;
3570 }
3571 } catch (Exception e) {
3572 // ignore
3573 } finally {
3574 try {
3575 socket.close();
3576 } catch (Exception e) {
3577 // ignore
3578 }
3579 }
3580 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003581 }
3582
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003583 /**
3584 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003585 * and not available in ConnectivityManager. Permissions are checked
3586 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003587 * @hide
3588 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003589 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003590 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003591 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003592 int user = UserHandle.getUserId(Binder.getCallingUid());
3593 synchronized(mVpns) {
3594 return mVpns.get(user).prepare(oldPackage, newPackage);
3595 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003596 }
3597
Chad Brubaker31de0b62013-07-11 13:29:30 -07003598 @Override
3599 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3600 enforceMarkNetworkSocketPermission();
3601 final long token = Binder.clearCallingIdentity();
3602 try {
3603 int mark = mNetd.getMarkForUid(uid);
3604 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3605 if (mark == -1) {
3606 mark = 0;
3607 }
3608 NetworkUtils.markSocket(socket.getFd(), mark);
3609 } catch (RemoteException e) {
3610 } finally {
3611 Binder.restoreCallingIdentity(token);
3612 }
3613 }
3614
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003615 /**
3616 * Configure a TUN interface and return its file descriptor. Parameters
3617 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003618 * and not available in ConnectivityManager. Permissions are checked in
3619 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003620 * @hide
3621 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003622 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003623 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003624 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003625 int user = UserHandle.getUserId(Binder.getCallingUid());
3626 synchronized(mVpns) {
3627 return mVpns.get(user).establish(config);
3628 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003629 }
3630
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003631 /**
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003632 * Start legacy VPN, controlling native daemons as needed. Creates a
3633 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003634 */
3635 @Override
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003636 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003637 throwIfLockdownEnabled();
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003638 final LinkProperties egress = getActiveLinkProperties();
3639 if (egress == null) {
3640 throw new IllegalStateException("Missing active network connection");
3641 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07003642 int user = UserHandle.getUserId(Binder.getCallingUid());
3643 synchronized(mVpns) {
3644 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3645 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003646 }
3647
3648 /**
3649 * Return the information of the ongoing legacy VPN. This method is used
3650 * by VpnSettings and not available in ConnectivityManager. Permissions
3651 * are checked in Vpn class.
3652 * @hide
3653 */
3654 @Override
3655 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003656 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003657 int user = UserHandle.getUserId(Binder.getCallingUid());
3658 synchronized(mVpns) {
3659 return mVpns.get(user).getLegacyVpnInfo();
3660 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003661 }
3662
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003663 /**
Chad Brubaker7dcfa2a2013-07-16 18:59:12 -07003664 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3665 * not available in ConnectivityManager.
3666 * Permissions are checked in Vpn class.
3667 * @hide
3668 */
3669 @Override
3670 public VpnConfig getVpnConfig() {
3671 int user = UserHandle.getUserId(Binder.getCallingUid());
3672 synchronized(mVpns) {
3673 return mVpns.get(user).getVpnConfig();
3674 }
3675 }
3676
3677 /**
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003678 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3679 * through NetworkStateTracker since it works differently. For example, it
3680 * needs to override DNS servers but never takes the default routes. It
3681 * relies on another data network, and it could keep existing connections
3682 * alive after reconnecting, switching between networks, or even resuming
3683 * from deep sleep. Calls from applications should be done synchronously
3684 * to avoid race conditions. As these are all hidden APIs, refactoring can
3685 * be done whenever a better abstraction is developed.
3686 */
3687 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003688 private VpnCallback() {
3689 }
3690
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003691 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003692 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003693 }
3694
Chad Brubakerccae0d32013-06-14 11:16:51 -07003695 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07003696 if (dnsServers == null) {
3697 restore();
3698 return;
3699 }
3700
3701 // Convert DNS servers into addresses.
3702 List<InetAddress> addresses = new ArrayList<InetAddress>();
3703 for (String address : dnsServers) {
3704 // Double check the addresses and remove invalid ones.
3705 try {
3706 addresses.add(InetAddress.parseNumericAddress(address));
3707 } catch (Exception e) {
3708 // ignore
3709 }
3710 }
3711 if (addresses.isEmpty()) {
3712 restore();
3713 return;
3714 }
3715
3716 // Concatenate search domains into a string.
3717 StringBuilder buffer = new StringBuilder();
3718 if (searchDomains != null) {
3719 for (String domain : searchDomains) {
3720 buffer.append(domain).append(' ');
3721 }
3722 }
3723 String domains = buffer.toString().trim();
3724
3725 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003726 synchronized (mDnsLock) {
Chad Brubaker45e721f2013-07-23 17:13:36 -07003727 updateDnsLocked("VPN", iface, addresses, domains, false);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003728 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003729
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003730 // Temporarily disable the default proxy (not global).
3731 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003732 mDefaultProxyDisabled = true;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003733 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003734 sendProxyBroadcast(null);
3735 }
3736 }
3737
3738 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003739 }
3740
Chia-chi Yehcc844502011-07-14 18:01:57 -07003741 public void restore() {
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003742 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003743 mDefaultProxyDisabled = false;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003744 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003745 sendProxyBroadcast(mDefaultProxy);
3746 }
3747 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003748 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07003749
3750 public void protect(ParcelFileDescriptor socket) {
3751 try {
3752 final int mark = mNetd.getMarkForProtect();
3753 NetworkUtils.markSocket(socket.getFd(), mark);
3754 } catch (RemoteException e) {
3755 }
3756 }
3757
3758 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3759 for (RouteInfo route : routes) {
3760 try {
3761 mNetd.setMarkedForwardingRoute(interfaze, route);
3762 } catch (RemoteException e) {
3763 }
3764 }
3765 }
3766
3767 public void setMarkedForwarding(String interfaze) {
3768 try {
3769 mNetd.setMarkedForwarding(interfaze);
3770 } catch (RemoteException e) {
3771 }
3772 }
3773
3774 public void clearMarkedForwarding(String interfaze) {
3775 try {
3776 mNetd.clearMarkedForwarding(interfaze);
3777 } catch (RemoteException e) {
3778 }
3779 }
3780
Robert Greenwalt68534c82013-09-24 11:05:57 -07003781 public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003782 int uidStart = uid * UserHandle.PER_USER_RANGE;
3783 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt68534c82013-09-24 11:05:57 -07003784 addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003785 }
3786
Robert Greenwalt68534c82013-09-24 11:05:57 -07003787 public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003788 int uidStart = uid * UserHandle.PER_USER_RANGE;
3789 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
Robert Greenwalt68534c82013-09-24 11:05:57 -07003790 clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003791 }
3792
Robert Greenwalt68534c82013-09-24 11:05:57 -07003793 public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
3794 boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003795 try {
3796 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
Robert Greenwalt68534c82013-09-24 11:05:57 -07003797 if (forwardDns) mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003798 } catch (RemoteException e) {
3799 }
3800
3801 }
3802
Robert Greenwalt68534c82013-09-24 11:05:57 -07003803 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
3804 boolean forwardDns) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003805 try {
3806 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
Robert Greenwalt68534c82013-09-24 11:05:57 -07003807 if (forwardDns) mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
Chad Brubakerccae0d32013-06-14 11:16:51 -07003808 } catch (RemoteException e) {
3809 }
3810
3811 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003812 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003813
3814 @Override
3815 public boolean updateLockdownVpn() {
Jeff Sharkeyc8a26872013-01-31 17:22:26 -08003816 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3817 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3818 return false;
3819 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003820
3821 // Tear down existing lockdown if profile was removed
3822 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3823 if (mLockdownEnabled) {
Kenny Roote3a37b22013-02-14 10:18:38 -08003824 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003825 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3826 return false;
3827 }
3828
3829 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3830 final VpnProfile profile = VpnProfile.decode(
3831 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubakerccae0d32013-06-14 11:16:51 -07003832 int user = UserHandle.getUserId(Binder.getCallingUid());
3833 synchronized(mVpns) {
3834 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3835 profile));
3836 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003837 } else {
3838 setLockdownTracker(null);
3839 }
3840
3841 return true;
3842 }
3843
3844 /**
3845 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3846 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3847 */
3848 private void setLockdownTracker(LockdownVpnTracker tracker) {
3849 // Shutdown any existing tracker
3850 final LockdownVpnTracker existing = mLockdownTracker;
3851 mLockdownTracker = null;
3852 if (existing != null) {
3853 existing.shutdown();
3854 }
3855
3856 try {
3857 if (tracker != null) {
3858 mNetd.setFirewallEnabled(true);
Jeff Sharkeyb103b252013-02-28 16:57:58 -08003859 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003860 mLockdownTracker = tracker;
3861 mLockdownTracker.init();
3862 } else {
3863 mNetd.setFirewallEnabled(false);
3864 }
3865 } catch (RemoteException e) {
3866 // ignored; NMS lives inside system_server
3867 }
3868 }
3869
3870 private void throwIfLockdownEnabled() {
3871 if (mLockdownEnabled) {
3872 throw new IllegalStateException("Unavailable in lockdown mode");
3873 }
3874 }
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003875
3876 public void supplyMessenger(int networkType, Messenger messenger) {
3877 enforceConnectivityInternalPermission();
3878
3879 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3880 mNetTrackers[networkType].supplyMessenger(messenger);
3881 }
3882 }
Robert Greenwalt308b9ac2013-04-22 11:13:02 -07003883
3884 public int findConnectionTypeForIface(String iface) {
3885 enforceConnectivityInternalPermission();
3886
3887 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3888 for (NetworkStateTracker tracker : mNetTrackers) {
3889 if (tracker != null) {
3890 LinkProperties lp = tracker.getLinkProperties();
3891 if (lp != null && iface.equals(lp.getInterfaceName())) {
3892 return tracker.getNetworkInfo().getType();
3893 }
3894 }
3895 }
3896 return ConnectivityManager.TYPE_NONE;
3897 }
Wink Saville690cb182013-06-29 21:10:57 -07003898
3899 /**
3900 * Have mobile data fail fast if enabled.
3901 *
3902 * @param enabled DctConstants.ENABLED/DISABLED
3903 */
3904 private void setEnableFailFastMobileData(int enabled) {
3905 int tag;
3906
3907 if (enabled == DctConstants.ENABLED) {
3908 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3909 } else {
3910 tag = mEnableFailFastMobileDataTag.get();
3911 }
3912 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3913 enabled));
3914 }
3915
Wink Savillebc588402013-08-16 17:17:28 -07003916 private boolean isMobileDataStateTrackerReady() {
3917 MobileDataStateTracker mdst =
Wink Saville89c87b92013-08-29 08:55:16 -07003918 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
Wink Savillebc588402013-08-16 17:17:28 -07003919 return (mdst != null) && (mdst.isReady());
3920 }
3921
Wink Saville89c87b92013-08-29 08:55:16 -07003922 /**
3923 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
3924 */
3925
3926 /**
3927 * No connection was possible to the network.
Wink Savillea3041492013-09-06 09:53:08 -07003928 * This is NOT a warm sim.
Wink Saville89c87b92013-08-29 08:55:16 -07003929 */
Wink Savillea3041492013-09-06 09:53:08 -07003930 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
Wink Saville89c87b92013-08-29 08:55:16 -07003931
3932 /**
3933 * A connection was made to the internet, all is well.
Wink Savillea3041492013-09-06 09:53:08 -07003934 * This is NOT a warm sim.
Wink Saville89c87b92013-08-29 08:55:16 -07003935 */
Wink Savillea3041492013-09-06 09:53:08 -07003936 private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
Wink Saville89c87b92013-08-29 08:55:16 -07003937
3938 /**
3939 * A connection was made but no dns server was available to resolve a name to address.
Wink Savillea3041492013-09-06 09:53:08 -07003940 * This is NOT a warm sim since provisioning network is supported.
Wink Saville89c87b92013-08-29 08:55:16 -07003941 */
Wink Savillea3041492013-09-06 09:53:08 -07003942 private static final int CMP_RESULT_CODE_NO_DNS = 2;
Wink Saville89c87b92013-08-29 08:55:16 -07003943
3944 /**
3945 * A connection was made but could not open a TCP connection.
Wink Savillea3041492013-09-06 09:53:08 -07003946 * This is NOT a warm sim since provisioning network is supported.
Wink Saville89c87b92013-08-29 08:55:16 -07003947 */
Wink Savillea3041492013-09-06 09:53:08 -07003948 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
3949
3950 /**
3951 * A connection was made but there was a redirection, we appear to be in walled garden.
3952 * This is an indication of a warm sim on a mobile network such as T-Mobile.
3953 */
3954 private static final int CMP_RESULT_CODE_REDIRECTED = 4;
Wink Saville89c87b92013-08-29 08:55:16 -07003955
3956 /**
3957 * The mobile network is a provisioning network.
Wink Savillea3041492013-09-06 09:53:08 -07003958 * This is an indication of a warm sim on a mobile network such as AT&T.
Wink Saville89c87b92013-08-29 08:55:16 -07003959 */
Wink Savillea3041492013-09-06 09:53:08 -07003960 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
Wink Saville89c87b92013-08-29 08:55:16 -07003961
Wink Savillea3041492013-09-06 09:53:08 -07003962 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
Wink Saville89c87b92013-08-29 08:55:16 -07003963
Wink Saville690cb182013-06-29 21:10:57 -07003964 @Override
Wink Saville89c87b92013-08-29 08:55:16 -07003965 public int checkMobileProvisioning(int suggestedTimeOutMs) {
3966 int timeOutMs = -1;
3967 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
3968 enforceConnectivityInternalPermission();
Wink Savillefdb84862013-07-02 10:55:14 -07003969
Wink Saville690cb182013-06-29 21:10:57 -07003970 final long token = Binder.clearCallingIdentity();
3971 try {
Wink Saville89c87b92013-08-29 08:55:16 -07003972 timeOutMs = suggestedTimeOutMs;
3973 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3974 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3975 }
3976
3977 // Check that mobile networks are supported
3978 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3979 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3980 if (DBG) log("checkMobileProvisioning: X no mobile network");
3981 return timeOutMs;
3982 }
3983
3984 // If we're already checking don't do it again
3985 // TODO: Add a queue of results...
3986 if (mIsCheckingMobileProvisioning.getAndSet(true)) {
3987 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
3988 return timeOutMs;
3989 }
3990
Wink Savillea65f4732013-10-03 08:34:46 -07003991 // Start off with mobile notification off
3992 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville89c87b92013-08-29 08:55:16 -07003993
Wink Saville690cb182013-06-29 21:10:57 -07003994 CheckMp checkMp = new CheckMp(mContext, this);
3995 CheckMp.CallBack cb = new CheckMp.CallBack() {
3996 @Override
3997 void onComplete(Integer result) {
Wink Saville89c87b92013-08-29 08:55:16 -07003998 if (DBG) log("CheckMp.onComplete: result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07003999 NetworkInfo ni =
4000 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4001 switch(result) {
Wink Saville89c87b92013-08-29 08:55:16 -07004002 case CMP_RESULT_CODE_CONNECTABLE:
Wink Savillea3041492013-09-06 09:53:08 -07004003 case CMP_RESULT_CODE_NO_CONNECTION:
4004 case CMP_RESULT_CODE_NO_DNS:
4005 case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Wink Saville89c87b92013-08-29 08:55:16 -07004006 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
Wink Saville690cb182013-06-29 21:10:57 -07004007 break;
4008 }
Wink Saville89c87b92013-08-29 08:55:16 -07004009 case CMP_RESULT_CODE_REDIRECTED: {
4010 if (DBG) log("CheckMp.onComplete: warm sim");
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004011 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004012 if (TextUtils.isEmpty(url)) {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004013 url = getMobileRedirectedProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004014 }
4015 if (TextUtils.isEmpty(url) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004016 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
Wink Savillea65f4732013-10-03 08:34:46 -07004017 setProvNotificationVisible(true,
4018 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville89c87b92013-08-29 08:55:16 -07004019 url);
Wink Saville690cb182013-06-29 21:10:57 -07004020 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004021 if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
Wink Saville690cb182013-06-29 21:10:57 -07004022 }
4023 break;
4024 }
Wink Savillea3041492013-09-06 09:53:08 -07004025 case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004026 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07004027 if (TextUtils.isEmpty(url) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004028 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
Wink Savillea65f4732013-10-03 08:34:46 -07004029 setProvNotificationVisible(true,
4030 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
Wink Saville89c87b92013-08-29 08:55:16 -07004031 url);
Wink Saville690cb182013-06-29 21:10:57 -07004032 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004033 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
Wink Saville690cb182013-06-29 21:10:57 -07004034 }
4035 break;
4036 }
4037 default: {
4038 loge("CheckMp.onComplete: ignore unexpected result=" + result);
4039 break;
4040 }
4041 }
Wink Saville89c87b92013-08-29 08:55:16 -07004042 mIsCheckingMobileProvisioning.set(false);
Wink Saville690cb182013-06-29 21:10:57 -07004043 }
4044 };
4045 CheckMp.Params params =
4046 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
Wink Saville89c87b92013-08-29 08:55:16 -07004047 if (DBG) log("checkMobileProvisioning: params=" + params);
Wink Saville690cb182013-06-29 21:10:57 -07004048 checkMp.execute(params);
4049 } finally {
4050 Binder.restoreCallingIdentity(token);
Wink Saville89c87b92013-08-29 08:55:16 -07004051 if (DBG) log("checkMobileProvisioning: X");
Wink Saville690cb182013-06-29 21:10:57 -07004052 }
4053 return timeOutMs;
4054 }
4055
4056 static class CheckMp extends
4057 AsyncTask<CheckMp.Params, Void, Integer> {
4058 private static final String CHECKMP_TAG = "CheckMp";
Wink Saville8fe05f12013-10-31 06:35:22 -07004059
4060 // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
4061 private static boolean mTestingFailures;
4062
4063 // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
4064 private static final int MAX_LOOPS = 4;
4065
4066 // Number of milli-seconds to complete all of the retires
Wink Saville690cb182013-06-29 21:10:57 -07004067 public static final int MAX_TIMEOUT_MS = 60000;
Wink Saville8fe05f12013-10-31 06:35:22 -07004068
4069 // The socket should retry only 5 seconds, the default is longer
Wink Saville690cb182013-06-29 21:10:57 -07004070 private static final int SOCKET_TIMEOUT_MS = 5000;
Wink Saville8fe05f12013-10-31 06:35:22 -07004071
4072 // Sleep time for network errors
4073 private static final int NET_ERROR_SLEEP_SEC = 3;
4074
4075 // Sleep time for network route establishment
4076 private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
4077
4078 // Short sleep time for polling :(
4079 private static final int POLLING_SLEEP_SEC = 1;
4080
Wink Saville690cb182013-06-29 21:10:57 -07004081 private Context mContext;
4082 private ConnectivityService mCs;
4083 private TelephonyManager mTm;
4084 private Params mParams;
4085
4086 /**
4087 * Parameters for AsyncTask.execute
4088 */
4089 static class Params {
4090 private String mUrl;
4091 private long mTimeOutMs;
4092 private CallBack mCb;
4093
4094 Params(String url, long timeOutMs, CallBack cb) {
4095 mUrl = url;
4096 mTimeOutMs = timeOutMs;
4097 mCb = cb;
4098 }
4099
4100 @Override
4101 public String toString() {
4102 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4103 }
4104 }
4105
Wink Saville8fe05f12013-10-31 06:35:22 -07004106 // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
4107 // issued by name or ip address, for Google its by name so when we construct
4108 // this HostnameVerifier we'll pass the original Uri and use it to verify
4109 // the host. If the host name in the original uril fails we'll test the
4110 // hostname parameter just incase things change.
4111 static class CheckMpHostnameVerifier implements HostnameVerifier {
4112 Uri mOrgUri;
4113
4114 CheckMpHostnameVerifier(Uri orgUri) {
4115 mOrgUri = orgUri;
4116 }
4117
4118 @Override
4119 public boolean verify(String hostname, SSLSession session) {
4120 HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
4121 String orgUriHost = mOrgUri.getHost();
4122 boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
4123 if (DBG) {
4124 log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
4125 + " orgUriHost=" + orgUriHost);
4126 }
4127 return retVal;
4128 }
4129 }
4130
Wink Saville690cb182013-06-29 21:10:57 -07004131 /**
4132 * The call back object passed in Params. onComplete will be called
4133 * on the main thread.
4134 */
4135 abstract static class CallBack {
4136 // Called on the main thread.
4137 abstract void onComplete(Integer result);
4138 }
4139
4140 public CheckMp(Context context, ConnectivityService cs) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004141 if (Build.IS_DEBUGGABLE) {
4142 mTestingFailures =
4143 SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
4144 } else {
4145 mTestingFailures = false;
4146 }
4147
Wink Saville690cb182013-06-29 21:10:57 -07004148 mContext = context;
4149 mCs = cs;
4150
4151 // Setup access to TelephonyService we'll be using.
4152 mTm = (TelephonyManager) mContext.getSystemService(
4153 Context.TELEPHONY_SERVICE);
4154 }
4155
4156 /**
4157 * Get the default url to use for the test.
4158 */
4159 public String getDefaultUrl() {
4160 // See http://go/clientsdns for usage approval
4161 String server = Settings.Global.getString(mContext.getContentResolver(),
4162 Settings.Global.CAPTIVE_PORTAL_SERVER);
4163 if (server == null) {
4164 server = "clients3.google.com";
4165 }
4166 return "http://" + server + "/generate_204";
4167 }
4168
4169 /**
4170 * Detect if its possible to connect to the http url. DNS based detection techniques
4171 * do not work at all hotspots. The best way to check is to perform a request to
4172 * a known address that fetches the data we expect.
4173 */
4174 private synchronized Integer isMobileOk(Params params) {
Wink Saville89c87b92013-08-29 08:55:16 -07004175 Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004176 Uri orgUri = Uri.parse(params.mUrl);
4177 Random rand = new Random();
4178 mParams = params;
4179
Wink Saville37e73122013-08-13 12:41:06 -07004180 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
Wink Saville89c87b92013-08-29 08:55:16 -07004181 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville39856712013-09-13 12:40:11 -07004182 log("isMobileOk: X not mobile capable result=" + result);
4183 return result;
4184 }
4185
4186 // See if we've already determined we've got a provisioning connection,
4187 // if so we don't need to do anything active.
4188 MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4189 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4190 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4191 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4192
4193 MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4194 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4195 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4196 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4197
4198 if (isDefaultProvisioning || isHipriProvisioning) {
4199 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4200 log("isMobileOk: X default || hipri is provisioning result=" + result);
Wink Saville37e73122013-08-13 12:41:06 -07004201 return result;
4202 }
Wink Saville690cb182013-06-29 21:10:57 -07004203
Wink Saville37e73122013-08-13 12:41:06 -07004204 try {
Wink Saville690cb182013-06-29 21:10:57 -07004205 // Continue trying to connect until time has run out
4206 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
Wink Saville4a165bb2013-08-07 11:02:57 -07004207
Wink Savillebc588402013-08-16 17:17:28 -07004208 if (!mCs.isMobileDataStateTrackerReady()) {
4209 // Wait for MobileDataStateTracker to be ready.
4210 if (DBG) log("isMobileOk: mdst is not ready");
4211 while(SystemClock.elapsedRealtime() < endTime) {
4212 if (mCs.isMobileDataStateTrackerReady()) {
4213 // Enable fail fast as we'll do retries here and use a
4214 // hipri connection so the default connection stays active.
4215 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4216 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4217 break;
4218 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004219 sleep(POLLING_SLEEP_SEC);
Wink Savillebc588402013-08-16 17:17:28 -07004220 }
4221 }
4222
4223 log("isMobileOk: start hipri url=" + params.mUrl);
4224
Wink Saville4a165bb2013-08-07 11:02:57 -07004225 // First wait until we can start using hipri
4226 Binder binder = new Binder();
4227 while(SystemClock.elapsedRealtime() < endTime) {
4228 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4229 Phone.FEATURE_ENABLE_HIPRI, binder);
4230 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4231 || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4232 log("isMobileOk: hipri started");
4233 break;
4234 }
4235 if (VDBG) log("isMobileOk: hipri not started yet");
Wink Saville89c87b92013-08-29 08:55:16 -07004236 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville8fe05f12013-10-31 06:35:22 -07004237 sleep(POLLING_SLEEP_SEC);
Wink Saville4a165bb2013-08-07 11:02:57 -07004238 }
4239
4240 // Continue trying to connect until time has run out
Wink Saville690cb182013-06-29 21:10:57 -07004241 while(SystemClock.elapsedRealtime() < endTime) {
4242 try {
4243 // Wait for hipri to connect.
4244 // TODO: Don't poll and handle situation where hipri fails
4245 // because default is retrying. See b/9569540
4246 NetworkInfo.State state = mCs
4247 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4248 if (state != NetworkInfo.State.CONNECTED) {
Wink Saville89c87b92013-08-29 08:55:16 -07004249 if (true/*VDBG*/) {
Wink Saville27f92732013-07-31 15:49:04 -07004250 log("isMobileOk: not connected ni=" +
Wink Saville690cb182013-06-29 21:10:57 -07004251 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
Wink Saville27f92732013-07-31 15:49:04 -07004252 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004253 sleep(POLLING_SLEEP_SEC);
Wink Saville89c87b92013-08-29 08:55:16 -07004254 result = CMP_RESULT_CODE_NO_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004255 continue;
4256 }
4257
Wink Saville89c87b92013-08-29 08:55:16 -07004258 // Hipri has started check if this is a provisioning url
4259 MobileDataStateTracker mdst = (MobileDataStateTracker)
4260 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4261 if (mdst.isProvisioningNetwork()) {
Wink Savillea3041492013-09-06 09:53:08 -07004262 result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
Wink Saville39856712013-09-13 12:40:11 -07004263 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
Wink Saville89c87b92013-08-29 08:55:16 -07004264 return result;
4265 } else {
4266 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4267 }
4268
Wink Saville690cb182013-06-29 21:10:57 -07004269 // Get of the addresses associated with the url host. We need to use the
4270 // address otherwise HttpURLConnection object will use the name to get
Wink Saville8fe05f12013-10-31 06:35:22 -07004271 // the addresses and will try every address but that will bypass the
Wink Saville690cb182013-06-29 21:10:57 -07004272 // route to host we setup and the connection could succeed as the default
4273 // interface might be connected to the internet via wifi or other interface.
4274 InetAddress[] addresses;
4275 try {
4276 addresses = InetAddress.getAllByName(orgUri.getHost());
4277 } catch (UnknownHostException e) {
Wink Saville89c87b92013-08-29 08:55:16 -07004278 result = CMP_RESULT_CODE_NO_DNS;
Wink Saville39856712013-09-13 12:40:11 -07004279 log("isMobileOk: X UnknownHostException result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004280 return result;
4281 }
4282 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4283
4284 // Get the type of addresses supported by this link
4285 LinkProperties lp = mCs.getLinkProperties(
4286 ConnectivityManager.TYPE_MOBILE_HIPRI);
Lorenzo Colitti662b96c2013-08-08 11:00:12 +09004287 boolean linkHasIpv4 = lp.hasIPv4Address();
4288 boolean linkHasIpv6 = lp.hasIPv6Address();
Wink Saville690cb182013-06-29 21:10:57 -07004289 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4290 + " linkHasIpv6=" + linkHasIpv6);
4291
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004292 final ArrayList<InetAddress> validAddresses =
4293 new ArrayList<InetAddress>(addresses.length);
Wink Saville690cb182013-06-29 21:10:57 -07004294
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004295 for (InetAddress addr : addresses) {
4296 if (((addr instanceof Inet4Address) && linkHasIpv4) ||
4297 ((addr instanceof Inet6Address) && linkHasIpv6)) {
4298 validAddresses.add(addr);
Wink Saville690cb182013-06-29 21:10:57 -07004299 }
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004300 }
4301
4302 if (validAddresses.size() == 0) {
4303 return CMP_RESULT_CODE_NO_CONNECTION;
4304 }
4305
4306 int addrTried = 0;
4307 while (true) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004308 // Loop through at most MAX_LOOPS valid addresses or until
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004309 // we run out of time
Wink Saville8fe05f12013-10-31 06:35:22 -07004310 if (addrTried++ >= MAX_LOOPS) {
4311 log("isMobileOk: too many loops tried - giving up");
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004312 break;
4313 }
4314 if (SystemClock.elapsedRealtime() >= endTime) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004315 log("isMobileOk: spend too much time - giving up");
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004316 break;
4317 }
4318
4319 InetAddress hostAddr = validAddresses.get(rand.nextInt(
4320 validAddresses.size()));
Wink Saville690cb182013-06-29 21:10:57 -07004321
4322 // Make a route to host so we check the specific interface.
4323 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4324 hostAddr.getAddress())) {
4325 // Wait a short time to be sure the route is established ??
4326 log("isMobileOk:"
4327 + " wait to establish route to hostAddr=" + hostAddr);
Wink Saville8fe05f12013-10-31 06:35:22 -07004328 sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
Wink Saville690cb182013-06-29 21:10:57 -07004329 } else {
4330 log("isMobileOk:"
4331 + " could not establish route to hostAddr=" + hostAddr);
Wink Saville8fe05f12013-10-31 06:35:22 -07004332 // Wait a short time before the next attempt
4333 sleep(NET_ERROR_SLEEP_SEC);
Wink Saville690cb182013-06-29 21:10:57 -07004334 continue;
4335 }
4336
Wink Saville8fe05f12013-10-31 06:35:22 -07004337 // Rewrite the url to have numeric address to use the specific route
4338 // using http for half the attempts and https for the other half.
4339 // Doing https first and http second as on a redirected walled garden
4340 // such as t-mobile uses we get a SocketTimeoutException: "SSL
4341 // handshake timed out" which we declare as
4342 // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
4343 // having http second we will be using logic used for some time.
4344 URL newUrl;
4345 String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
4346 newUrl = new URL(scheme, hostAddr.getHostAddress(),
4347 orgUri.getPath());
Wink Saville690cb182013-06-29 21:10:57 -07004348 log("isMobileOk: newUrl=" + newUrl);
4349
4350 HttpURLConnection urlConn = null;
4351 try {
Wink Saville8fe05f12013-10-31 06:35:22 -07004352 // Open the connection set the request headers and get the response
4353 urlConn = (HttpURLConnection)newUrl.openConnection(
Wink Saville690cb182013-06-29 21:10:57 -07004354 java.net.Proxy.NO_PROXY);
Wink Saville8fe05f12013-10-31 06:35:22 -07004355 if (scheme.equals("https")) {
4356 ((HttpsURLConnection)urlConn).setHostnameVerifier(
4357 new CheckMpHostnameVerifier(orgUri));
4358 }
Wink Saville690cb182013-06-29 21:10:57 -07004359 urlConn.setInstanceFollowRedirects(false);
4360 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4361 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4362 urlConn.setUseCaches(false);
4363 urlConn.setAllowUserInteraction(false);
Lorenzo Colittie25513d2013-10-08 10:41:25 +09004364 // Set the "Connection" to "Close" as by default "Keep-Alive"
4365 // is used which is useless in this case.
Wink Saville690cb182013-06-29 21:10:57 -07004366 urlConn.setRequestProperty("Connection", "close");
4367 int responseCode = urlConn.getResponseCode();
Wink Savillea3041492013-09-06 09:53:08 -07004368
4369 // For debug display the headers
4370 Map<String, List<String>> headers = urlConn.getHeaderFields();
4371 log("isMobileOk: headers=" + headers);
4372
4373 // Close the connection
Wink Saville690cb182013-06-29 21:10:57 -07004374 urlConn.disconnect();
4375 urlConn = null;
Wink Savillea3041492013-09-06 09:53:08 -07004376
Wink Saville8fe05f12013-10-31 06:35:22 -07004377 if (mTestingFailures) {
4378 // Pretend no connection, this tests using http and https
4379 result = CMP_RESULT_CODE_NO_CONNECTION;
4380 log("isMobileOk: TESTING_FAILURES, pretend no connction");
4381 continue;
4382 }
4383
Wink Savillea3041492013-09-06 09:53:08 -07004384 if (responseCode == 204) {
4385 // Return
Wink Savillea3041492013-09-06 09:53:08 -07004386 result = CMP_RESULT_CODE_CONNECTABLE;
Wink Saville8fe05f12013-10-31 06:35:22 -07004387 log("isMobileOk: X got expected responseCode=" + responseCode
Wink Saville39856712013-09-13 12:40:11 -07004388 + " result=" + result);
Wink Savillea3041492013-09-06 09:53:08 -07004389 return result;
4390 } else {
4391 // Retry to be sure this was redirected, we've gotten
4392 // occasions where a server returned 200 even though
4393 // the device didn't have a "warm" sim.
4394 log("isMobileOk: not expected responseCode=" + responseCode);
Robert Greenwalt6bfeaeb2013-10-14 18:03:02 -07004395 // TODO - it would be nice in the single-address case to do
4396 // another DNS resolve here, but flushing the cache is a bit
4397 // heavy-handed.
Wink Savillea3041492013-09-06 09:53:08 -07004398 result = CMP_RESULT_CODE_REDIRECTED;
4399 }
Wink Saville690cb182013-06-29 21:10:57 -07004400 } catch (Exception e) {
Wink Saville8fe05f12013-10-31 06:35:22 -07004401 log("isMobileOk: HttpURLConnection Exception" + e);
Wink Savillea3041492013-09-06 09:53:08 -07004402 result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
Wink Saville690cb182013-06-29 21:10:57 -07004403 if (urlConn != null) {
4404 urlConn.disconnect();
4405 urlConn = null;
4406 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004407 sleep(NET_ERROR_SLEEP_SEC);
4408 continue;
Wink Saville690cb182013-06-29 21:10:57 -07004409 }
4410 }
Wink Saville39856712013-09-13 12:40:11 -07004411 log("isMobileOk: X loops|timed out result=" + result);
Wink Saville690cb182013-06-29 21:10:57 -07004412 return result;
4413 } catch (Exception e) {
4414 log("isMobileOk: Exception e=" + e);
4415 continue;
4416 }
4417 }
4418 log("isMobileOk: timed out");
4419 } finally {
4420 log("isMobileOk: F stop hipri");
4421 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4422 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4423 Phone.FEATURE_ENABLE_HIPRI);
Wink Saville89c87b92013-08-29 08:55:16 -07004424
4425 // Wait for hipri to disconnect.
4426 long endTime = SystemClock.elapsedRealtime() + 5000;
4427
4428 while(SystemClock.elapsedRealtime() < endTime) {
4429 NetworkInfo.State state = mCs
4430 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4431 if (state != NetworkInfo.State.DISCONNECTED) {
4432 if (VDBG) {
4433 log("isMobileOk: connected ni=" +
4434 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4435 }
Wink Saville8fe05f12013-10-31 06:35:22 -07004436 sleep(POLLING_SLEEP_SEC);
Wink Saville89c87b92013-08-29 08:55:16 -07004437 continue;
4438 }
4439 }
4440
Wink Saville690cb182013-06-29 21:10:57 -07004441 log("isMobileOk: X result=" + result);
4442 }
4443 return result;
4444 }
4445
4446 @Override
4447 protected Integer doInBackground(Params... params) {
4448 return isMobileOk(params[0]);
4449 }
4450
4451 @Override
4452 protected void onPostExecute(Integer result) {
4453 log("onPostExecute: result=" + result);
4454 if ((mParams != null) && (mParams.mCb != null)) {
4455 mParams.mCb.onComplete(result);
4456 }
4457 }
4458
4459 private String inetAddressesToString(InetAddress[] addresses) {
4460 StringBuffer sb = new StringBuffer();
4461 boolean firstTime = true;
4462 for(InetAddress addr : addresses) {
4463 if (firstTime) {
4464 firstTime = false;
4465 } else {
4466 sb.append(",");
4467 }
4468 sb.append(addr);
4469 }
4470 return sb.toString();
4471 }
4472
4473 private void printNetworkInfo() {
4474 boolean hasIccCard = mTm.hasIccCard();
4475 int simState = mTm.getSimState();
4476 log("hasIccCard=" + hasIccCard
4477 + " simState=" + simState);
4478 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4479 if (ni != null) {
4480 log("ni.length=" + ni.length);
4481 for (NetworkInfo netInfo: ni) {
4482 log("netInfo=" + netInfo.toString());
4483 }
4484 } else {
4485 log("no network info ni=null");
4486 }
4487 }
4488
4489 /**
4490 * Sleep for a few seconds then return.
4491 * @param seconds
4492 */
4493 private static void sleep(int seconds) {
4494 try {
4495 Thread.sleep(seconds * 1000);
4496 } catch (InterruptedException e) {
4497 e.printStackTrace();
4498 }
4499 }
4500
Wink Saville8fe05f12013-10-31 06:35:22 -07004501 private static void log(String s) {
Wink Saville690cb182013-06-29 21:10:57 -07004502 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4503 }
4504 }
4505
Wink Saville89c87b92013-08-29 08:55:16 -07004506 // TODO: Move to ConnectivityManager and make public?
4507 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4508 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
Wink Saville690cb182013-06-29 21:10:57 -07004509
Wink Saville89c87b92013-08-29 08:55:16 -07004510 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4511 @Override
4512 public void onReceive(Context context, Intent intent) {
4513 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4514 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4515 }
4516 }
4517 };
4518
4519 private void handleMobileProvisioningAction(String url) {
4520 // Notication mark notification as not visible
Wink Savillea65f4732013-10-03 08:34:46 -07004521 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
Wink Saville89c87b92013-08-29 08:55:16 -07004522
4523 // If provisioning network handle as a special case,
4524 // otherwise launch browser with the intent directly.
4525 NetworkInfo ni = getProvisioningNetworkInfo();
Wink Saville860f5282013-09-05 12:02:25 -07004526 if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
Wink Saville89c87b92013-08-29 08:55:16 -07004527 if (DBG) log("handleMobileProvisioningAction: on provisioning network");
4528 MobileDataStateTracker mdst = (MobileDataStateTracker)
4529 mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4530 mdst.enableMobileProvisioning(url);
4531 } else {
4532 if (DBG) log("handleMobileProvisioningAction: on default network");
Andrew Flynn2f158282013-10-11 10:16:31 -07004533 // Check for apps that can handle provisioning first
4534 Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP);
4535 provisioningIntent.addCategory(TelephonyIntents.CATEGORY_MCCMNC_PREFIX
4536 + mTelephonyManager.getSimOperator());
4537 if (mContext.getPackageManager().resolveActivity(provisioningIntent, 0 /* flags */)
4538 != null) {
4539 provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4540 Intent.FLAG_ACTIVITY_NEW_TASK);
4541 mContext.startActivity(provisioningIntent);
4542 } else {
4543 // If no apps exist, use standard URL ACTION_VIEW method
4544 Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
4545 Intent.CATEGORY_APP_BROWSER);
4546 newIntent.setData(Uri.parse(url));
4547 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4548 Intent.FLAG_ACTIVITY_NEW_TASK);
4549 try {
4550 mContext.startActivity(newIntent);
4551 } catch (ActivityNotFoundException e) {
4552 loge("handleMobileProvisioningAction: startActivity failed" + e);
4553 }
Wink Saville89c87b92013-08-29 08:55:16 -07004554 }
4555 }
4556 }
4557
4558 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4559 private volatile boolean mIsNotificationVisible = false;
4560
4561 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4562 String url) {
4563 if (DBG) {
4564 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4565 + " extraInfo=" + extraInfo + " url=" + url);
4566 }
Wink Saville690cb182013-06-29 21:10:57 -07004567
4568 Resources r = Resources.getSystem();
4569 NotificationManager notificationManager = (NotificationManager) mContext
4570 .getSystemService(Context.NOTIFICATION_SERVICE);
4571
4572 if (visible) {
4573 CharSequence title;
4574 CharSequence details;
4575 int icon;
Wink Saville89c87b92013-08-29 08:55:16 -07004576 Intent intent;
4577 Notification notification = new Notification();
4578 switch (networkType) {
Wink Saville690cb182013-06-29 21:10:57 -07004579 case ConnectivityManager.TYPE_WIFI:
Wink Saville690cb182013-06-29 21:10:57 -07004580 title = r.getString(R.string.wifi_available_sign_in, 0);
4581 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville89c87b92013-08-29 08:55:16 -07004582 extraInfo);
Wink Saville690cb182013-06-29 21:10:57 -07004583 icon = R.drawable.stat_notify_wifi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004584 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4585 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4586 Intent.FLAG_ACTIVITY_NEW_TASK);
4587 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004588 break;
4589 case ConnectivityManager.TYPE_MOBILE:
4590 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Saville690cb182013-06-29 21:10:57 -07004591 title = r.getString(R.string.network_available_sign_in, 0);
4592 // TODO: Change this to pull from NetworkInfo once a printable
4593 // name has been added to it
4594 details = mTelephonyManager.getNetworkOperatorName();
4595 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004596 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4597 intent.putExtra("EXTRA_URL", url);
4598 intent.setFlags(0);
4599 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004600 break;
4601 default:
Wink Saville690cb182013-06-29 21:10:57 -07004602 title = r.getString(R.string.network_available_sign_in, 0);
4603 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville89c87b92013-08-29 08:55:16 -07004604 extraInfo);
Wink Saville690cb182013-06-29 21:10:57 -07004605 icon = R.drawable.stat_notify_rssi_in_range;
Wink Saville89c87b92013-08-29 08:55:16 -07004606 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4607 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4608 Intent.FLAG_ACTIVITY_NEW_TASK);
4609 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
Wink Saville690cb182013-06-29 21:10:57 -07004610 break;
4611 }
4612
Wink Saville690cb182013-06-29 21:10:57 -07004613 notification.when = 0;
4614 notification.icon = icon;
4615 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Saville690cb182013-06-29 21:10:57 -07004616 notification.tickerText = title;
4617 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4618
Wink Saville89c87b92013-08-29 08:55:16 -07004619 try {
Wink Savillea65f4732013-10-03 08:34:46 -07004620 notificationManager.notify(NOTIFICATION_ID, networkType, notification);
Wink Saville89c87b92013-08-29 08:55:16 -07004621 } catch (NullPointerException npe) {
4622 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4623 npe.printStackTrace();
4624 }
Wink Saville690cb182013-06-29 21:10:57 -07004625 } else {
Wink Saville89c87b92013-08-29 08:55:16 -07004626 try {
Wink Savillea65f4732013-10-03 08:34:46 -07004627 notificationManager.cancel(NOTIFICATION_ID, networkType);
Wink Saville89c87b92013-08-29 08:55:16 -07004628 } catch (NullPointerException npe) {
4629 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4630 npe.printStackTrace();
4631 }
Wink Saville690cb182013-06-29 21:10:57 -07004632 }
Wink Saville89c87b92013-08-29 08:55:16 -07004633 mIsNotificationVisible = visible;
Wink Saville690cb182013-06-29 21:10:57 -07004634 }
4635
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004636 /** Location to an updatable file listing carrier provisioning urls.
4637 * An example:
4638 *
4639 * <?xml version="1.0" encoding="utf-8"?>
4640 * <provisioningUrls>
4641 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4642 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4643 * </provisioningUrls>
4644 */
4645 private static final String PROVISIONING_URL_PATH =
4646 "/data/misc/radio/provisioning_urls.xml";
4647 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville690cb182013-06-29 21:10:57 -07004648
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004649 /** XML tag for root element. */
4650 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4651 /** XML tag for individual url */
4652 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4653 /** XML tag for redirected url */
4654 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4655 /** XML attribute for mcc */
4656 private static final String ATTR_MCC = "mcc";
4657 /** XML attribute for mnc */
4658 private static final String ATTR_MNC = "mnc";
4659
4660 private static final int REDIRECTED_PROVISIONING = 1;
4661 private static final int PROVISIONING = 2;
4662
4663 private String getProvisioningUrlBaseFromFile(int type) {
4664 FileReader fileReader = null;
4665 XmlPullParser parser = null;
4666 Configuration config = mContext.getResources().getConfiguration();
4667 String tagType;
4668
4669 switch (type) {
4670 case PROVISIONING:
4671 tagType = TAG_PROVISIONING_URL;
4672 break;
4673 case REDIRECTED_PROVISIONING:
4674 tagType = TAG_REDIRECTED_URL;
4675 break;
4676 default:
4677 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4678 type);
4679 }
4680
4681 try {
4682 fileReader = new FileReader(mProvisioningUrlFile);
4683 parser = Xml.newPullParser();
4684 parser.setInput(fileReader);
4685 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4686
4687 while (true) {
4688 XmlUtils.nextElement(parser);
4689
4690 String element = parser.getName();
4691 if (element == null) break;
4692
4693 if (element.equals(tagType)) {
4694 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4695 try {
4696 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4697 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4698 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4699 parser.next();
4700 if (parser.getEventType() == XmlPullParser.TEXT) {
4701 return parser.getText();
4702 }
4703 }
4704 }
4705 } catch (NumberFormatException e) {
4706 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4707 }
4708 }
4709 }
4710 return null;
4711 } catch (FileNotFoundException e) {
4712 loge("Carrier Provisioning Urls file not found");
4713 } catch (XmlPullParserException e) {
4714 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4715 } catch (IOException e) {
4716 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4717 } finally {
4718 if (fileReader != null) {
4719 try {
4720 fileReader.close();
4721 } catch (IOException e) {}
4722 }
4723 }
4724 return null;
4725 }
4726
Wink Savillef714b7f2013-07-20 20:31:59 -07004727 @Override
4728 public String getMobileRedirectedProvisioningUrl() {
4729 enforceConnectivityInternalPermission();
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004730 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4731 if (TextUtils.isEmpty(url)) {
4732 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4733 }
4734 return url;
4735 }
4736
Wink Savillef714b7f2013-07-20 20:31:59 -07004737 @Override
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004738 public String getMobileProvisioningUrl() {
4739 enforceConnectivityInternalPermission();
4740 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4741 if (TextUtils.isEmpty(url)) {
4742 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Savillef714b7f2013-07-20 20:31:59 -07004743 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004744 } else {
Wink Savillef714b7f2013-07-20 20:31:59 -07004745 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004746 }
Wink Savilledfabd992013-07-10 23:00:07 -07004747 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville690cb182013-06-29 21:10:57 -07004748 if (!TextUtils.isEmpty(url)) {
Wink Savilledfabd992013-07-10 23:00:07 -07004749 String phoneNumber = mTelephonyManager.getLine1Number();
4750 if (TextUtils.isEmpty(phoneNumber)) {
4751 phoneNumber = "0000000000";
4752 }
Wink Saville690cb182013-06-29 21:10:57 -07004753 url = String.format(url,
4754 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4755 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savilledfabd992013-07-10 23:00:07 -07004756 phoneNumber /* Phone numer */);
Wink Saville690cb182013-06-29 21:10:57 -07004757 }
4758
Wink Saville690cb182013-06-29 21:10:57 -07004759 return url;
4760 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07004761
Wink Saville89c87b92013-08-29 08:55:16 -07004762 @Override
4763 public void setProvisioningNotificationVisible(boolean visible, int networkType,
4764 String extraInfo, String url) {
4765 enforceConnectivityInternalPermission();
4766 setProvNotificationVisible(visible, networkType, extraInfo, url);
4767 }
Wink Saville3ade4872013-08-29 14:57:08 -07004768
Yuhao Zheng15019892013-09-09 17:00:04 -07004769 @Override
4770 public void setAirplaneMode(boolean enable) {
4771 enforceConnectivityInternalPermission();
Yuhao Zheng15019892013-09-09 17:00:04 -07004772 final long ident = Binder.clearCallingIdentity();
4773 try {
Yuhao Zheng82579362013-09-11 09:36:41 -07004774 final ContentResolver cr = mContext.getContentResolver();
4775 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
4776 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
4777 intent.putExtra("state", enable);
Yuhao Zheng15019892013-09-09 17:00:04 -07004778 mContext.sendBroadcast(intent);
4779 } finally {
4780 Binder.restoreCallingIdentity(ident);
4781 }
4782 }
4783
Chad Brubakerccae0d32013-06-14 11:16:51 -07004784 private void onUserStart(int userId) {
4785 synchronized(mVpns) {
4786 Vpn userVpn = mVpns.get(userId);
4787 if (userVpn != null) {
4788 loge("Starting user already has a VPN");
4789 return;
4790 }
4791 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4792 mVpns.put(userId, userVpn);
4793 userVpn.startMonitoring(mContext, mTrackerHandler);
4794 }
4795 }
4796
4797 private void onUserStop(int userId) {
4798 synchronized(mVpns) {
4799 Vpn userVpn = mVpns.get(userId);
4800 if (userVpn == null) {
4801 loge("Stopping user has no VPN");
4802 return;
4803 }
4804 mVpns.delete(userId);
4805 }
4806 }
4807
4808 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4809 @Override
4810 public void onReceive(Context context, Intent intent) {
4811 final String action = intent.getAction();
4812 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4813 if (userId == UserHandle.USER_NULL) return;
4814
4815 if (Intent.ACTION_USER_STARTING.equals(action)) {
4816 onUserStart(userId);
4817 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4818 onUserStop(userId);
4819 }
4820 }
4821 };
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004822
4823 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004824 public LinkQualityInfo getLinkQualityInfo(int networkType) {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004825 enforceAccessPermission();
4826 if (isNetworkTypeValid(networkType)) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004827 return mNetTrackers[networkType].getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004828 } else {
4829 return null;
4830 }
4831 }
4832
4833 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004834 public LinkQualityInfo getActiveLinkQualityInfo() {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004835 enforceAccessPermission();
4836 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004837 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004838 } else {
4839 return null;
4840 }
4841 }
4842
4843 @Override
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004844 public LinkQualityInfo[] getAllLinkQualityInfo() {
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004845 enforceAccessPermission();
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004846 final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004847 for (NetworkStateTracker tracker : mNetTrackers) {
4848 if (tracker != null) {
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004849 LinkQualityInfo li = tracker.getLinkQualityInfo();
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004850 if (li != null) {
4851 result.add(li);
4852 }
4853 }
4854 }
4855
Vinit Deshapnde69386b32013-09-04 14:11:24 -07004856 return result.toArray(new LinkQualityInfo[result.size()]);
Vinit Deshapndedb7abcb2013-08-21 13:09:01 -07004857 }
4858
4859 /* Infrastructure for network sampling */
4860
4861 private void handleNetworkSamplingTimeout() {
4862
4863 log("Sampling interval elapsed, updating statistics ..");
4864
4865 // initialize list of interfaces ..
4866 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
4867 new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
4868 for (NetworkStateTracker tracker : mNetTrackers) {
4869 if (tracker != null) {
4870 String ifaceName = tracker.getNetworkInterfaceName();
4871 if (ifaceName != null) {
4872 mapIfaceToSample.put(ifaceName, null);
4873 }
4874 }
4875 }
4876
4877 // Read samples for all interfaces
4878 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
4879
4880 // process samples for all networks
4881 for (NetworkStateTracker tracker : mNetTrackers) {
4882 if (tracker != null) {
4883 String ifaceName = tracker.getNetworkInterfaceName();
4884 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
4885 if (ss != null) {
4886 // end the previous sampling cycle
4887 tracker.stopSampling(ss);
4888 // start a new sampling cycle ..
4889 tracker.startSampling(ss);
4890 }
4891 }
4892 }
4893
4894 log("Done.");
4895
4896 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
4897 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
4898 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
4899
4900 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
4901
4902 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
4903 }
4904
4905 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
4906 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
4907 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
4908 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004909}