blob: 3a4b7e382f57001bba50c9e2206b912e5a1fa723 [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
Wink Saville32506bc2013-06-29 21:10:57 -070034import android.app.Notification;
35import android.app.NotificationManager;
36import android.app.PendingIntent;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080037import android.bluetooth.BluetoothTetheringDataTracker;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070038import android.content.BroadcastReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080039import android.content.ContentResolver;
40import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090041import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080042import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project28527d22009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
tk.mun093f55c2011-10-13 22:51:57 +090045import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070046import android.database.ContentObserver;
Irfan Sheriff0ad0d132012-08-16 12:49:23 -070047import android.net.CaptivePortalTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080048import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080049import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080050import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070056import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080057import android.net.LinkProperties;
Wink Saville32506bc2013-06-29 21:10:57 -070058import android.net.Uri;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070059import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080060import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070061import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080062import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070063import android.net.NetworkInfo.DetailedState;
Wink Saville32506bc2013-06-29 21:10:57 -070064import android.net.NetworkInfo.State;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070065import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070066import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080067import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070068import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070069import android.net.Proxy;
70import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070071import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080072import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090073import android.net.wimax.WimaxManagerConstants;
Wink Saville32506bc2013-06-29 21:10:57 -070074import android.os.AsyncTask;
The Android Open Source Project28527d22009-03-03 19:31:44 -080075import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040076import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080077import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070078import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070079import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070080import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080081import android.os.Looper;
82import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070083import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070084import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070085import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -070086import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070087import android.os.RemoteException;
Wink Saville32506bc2013-06-29 21:10:57 -070088import android.os.ResultReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080089import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070090import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080091import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -070092import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080093import android.provider.Settings;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070094import android.security.Credentials;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -070095import android.security.KeyStore;
Wink Saville32506bc2013-06-29 21:10:57 -070096import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070097import android.text.TextUtils;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080098import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070099import android.util.SparseIntArray;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700100import android.util.SparseArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800101
Wink Saville32506bc2013-06-29 21:10:57 -0700102import com.android.internal.R;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700103import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700104import com.android.internal.net.VpnConfig;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700105import com.android.internal.net.VpnProfile;
Wink Saville32506bc2013-06-29 21:10:57 -0700106import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700107import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700108import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700109import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700110import com.android.server.am.BatteryStatsService;
John Spurlock1f5cec72013-06-24 14:20:23 -0400111import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900112import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800113import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700114import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700115import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700116import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700117import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700118import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700119
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700120import com.android.internal.annotations.GuardedBy;
121
tk.mun093f55c2011-10-13 22:51:57 +0900122import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700123
The Android Open Source Project28527d22009-03-03 19:31:44 -0800124import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700125import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800126import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900127import java.lang.reflect.Constructor;
Wink Saville32506bc2013-06-29 21:10:57 -0700128import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700129import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700130import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700131import java.net.InetAddress;
Wink Saville32506bc2013-06-29 21:10:57 -0700132import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700133import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700134import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700135import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700136import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700137import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700138import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700139import java.util.List;
Wink Saville32506bc2013-06-29 21:10:57 -0700140import java.util.Random;
141import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800142
143/**
144 * @hide
145 */
146public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700147 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800148
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700149 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700150 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800151
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700152 private static final boolean LOGD_RULES = false;
153
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700154 // TODO: create better separation between radio types and network types
155
Robert Greenwalt2034b912009-08-12 16:08:25 -0700156 // how long to wait before switching back to a radio's default network
157 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
158 // system property that can override the above value
159 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
160 "android.telephony.apn-restore";
161
Wink Saville32506bc2013-06-29 21:10:57 -0700162 // Default value if FAIL_FAST_TIME_MS is not set
163 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
164 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
165 private static final String FAIL_FAST_TIME_MS =
166 "persist.radio.fail_fast_time_ms";
167
Robert Greenwaltbd492212011-05-06 17:10:53 -0700168 // used in recursive route setting to add gateways for the host for which
169 // a host route was requested.
170 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
171
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800172 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800173 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800174
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700175 private KeyStore mKeyStore;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700176
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700177 @GuardedBy("mVpns")
178 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700179 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700180
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700181 private boolean mLockdownEnabled;
182 private LockdownVpnTracker mLockdownTracker;
183
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900184 private Nat464Xlat mClat;
185
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700186 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
187 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700188 /** Currently active network rules by UID. */
189 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700190 /** Set of ifaces that are costly. */
191 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700192
The Android Open Source Project28527d22009-03-03 19:31:44 -0800193 /**
194 * Sometimes we want to refer to the individual network state
195 * trackers separately, and sometimes we just want to treat them
196 * abstractly.
197 */
198 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700199
Irfan Sheriff0ad0d132012-08-16 12:49:23 -0700200 /* Handles captive portal check on a network */
201 private CaptivePortalTracker mCaptivePortalTracker;
202
Robert Greenwalt2034b912009-08-12 16:08:25 -0700203 /**
Wink Saville051a6642011-07-13 13:44:13 -0700204 * The link properties that define the current links
205 */
206 private LinkProperties mCurrentLinkProperties[];
207
208 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700209 * A per Net list of the PID's that requested access to the net
210 * used both as a refcount and for per-PID DNS selection
211 */
Mattias Falkd697aa22011-08-23 14:15:13 +0200212 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700213
Robert Greenwalt2034b912009-08-12 16:08:25 -0700214 // priority order of the nettrackers
215 // (excluding dynamically set mNetworkPreference)
216 // TODO - move mNetworkTypePreference into this
217 private int[] mPriorityList;
218
The Android Open Source Project28527d22009-03-03 19:31:44 -0800219 private Context mContext;
220 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700221 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700222 // 0 is full bad, 100 is full good
Wink Saville151eaa62013-01-31 00:30:13 +0000223 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700224 private int mDefaultInetConditionPublished = 0;
225 private boolean mInetConditionChangeInFlight = false;
226 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800227
Chia-chi Yehcc844502011-07-14 18:01:57 -0700228 private Object mDnsLock = new Object();
Robert Greenwalte41e3b32013-02-11 15:25:10 -0800229 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700230 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800231
232 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700233 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800234
Robert Greenwalt355205c2011-05-10 15:05:02 -0700235 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700236 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700237
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700238 private static final int ENABLED = 1;
239 private static final int DISABLED = 0;
240
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700241 private static final boolean ADD = true;
242 private static final boolean REMOVE = false;
243
244 private static final boolean TO_DEFAULT_TABLE = true;
245 private static final boolean TO_SECONDARY_TABLE = false;
246
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700247 /**
248 * used internally as a delayed event to make us switch back to the
249 * default network
250 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700251 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700252
253 /**
254 * used internally to change our mobile data enabled flag
255 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700256 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700257
258 /**
259 * used internally to change our network preference setting
260 * arg1 = networkType to prefer
261 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700262 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700263
264 /**
265 * used internally to synchronize inet condition reports
266 * arg1 = networkType
267 * arg2 = condition (0 bad, 100 good)
268 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700269 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700270
271 /**
272 * used internally to mark the end of inet condition hold periods
273 * arg1 = networkType
274 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700275 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700276
277 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700278 * used internally to set enable/disable cellular data
279 * arg1 = ENBALED or DISABLED
280 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700281 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700282
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700283 /**
284 * used internally to clear a wakelock when transitioning
285 * from one net to another
286 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700287 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700288
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700289 /**
290 * used internally to reload global proxy settings
291 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700292 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700293
Robert Greenwalt34848c02011-03-25 13:09:25 -0700294 /**
295 * used internally to set external dependency met/unmet
296 * arg1 = ENABLED (met) or DISABLED (unmet)
297 * arg2 = NetworkType
298 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700299 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700300
Chia-chi Yehcc844502011-07-14 18:01:57 -0700301 /**
302 * used internally to restore DNS properties back to the
303 * default network
304 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700305 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700306
Wink Saville7e4333c2011-08-05 11:40:22 -0700307 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700308 * used internally to send a sticky broadcast delayed.
309 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700310 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700311
Jeff Sharkey805662d2011-08-19 02:24:24 -0700312 /**
313 * Used internally to
314 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
315 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700316 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700317
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700318 private static final int EVENT_VPN_STATE_CHANGED = 14;
319
Wink Saville32506bc2013-06-29 21:10:57 -0700320 /**
321 * Used internally to disable fail fast of mobile data
322 */
323 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 15;
324
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700325 /** Handler used for internal events. */
326 private InternalHandler mHandler;
327 /** Handler used for incoming {@link NetworkStateTracker} events. */
328 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700329
330 // list of DeathRecipients used to make sure features are turned off when
331 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500332 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700333
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400334 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800335 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400336
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700337 private PowerManager.WakeLock mNetTransitionWakeLock;
338 private String mNetTransitionWakeLockCausedBy = "";
339 private int mNetTransitionWakeLockSerialNumber;
340 private int mNetTransitionWakeLockTimeout;
341
Robert Greenwalt94daa182010-09-01 11:34:05 -0700342 private InetAddress mDefaultDns;
343
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700344 // this collection is used to refcount the added routes - if there are none left
345 // it's time to remove the route from the route table
346 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
347
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700348 // used in DBG mode to track inet condition reports
349 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
350 private ArrayList mInetLog;
351
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700352 // track the current default http proxy - tell the world if we get a new one (real change)
353 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltf9661d32013-04-05 17:14:19 -0700354 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700355 private boolean mDefaultProxyDisabled = false;
356
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700357 // track the global proxy.
358 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700359
360 private SettingsObserver mSettingsObserver;
361
Robert Greenwalt34848c02011-03-25 13:09:25 -0700362 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700363 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700364
Robert Greenwalt12c44552009-12-07 11:33:18 -0800365 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700366 public int mSimultaneity;
367 public int mType;
368 public RadioAttributes(String init) {
369 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700370 mType = Integer.parseInt(fragments[0]);
371 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700372 }
373 }
374 RadioAttributes[] mRadioAttributes;
375
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700376 // the set of network types that can only be enabled by system/sig apps
377 List mProtectedNetworks;
378
John Spurlock1f5cec72013-06-24 14:20:23 -0400379 private DataConnectionStats mDataConnectionStats;
Wink Saville32506bc2013-06-29 21:10:57 -0700380 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
381
382 TelephonyManager mTelephonyManager;
John Spurlock1f5cec72013-06-24 14:20:23 -0400383
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700384 public ConnectivityService(Context context, INetworkManagementService netd,
385 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700386 // Currently, omitting a NetworkFactory will create one internally
387 // TODO: create here when we have cleaner WiMAX support
388 this(context, netd, statsService, policyManager, null);
389 }
390
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700391 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700392 INetworkStatsService statsService, INetworkPolicyManager policyManager,
393 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800394 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800395
Wink Saville775aad62010-09-02 19:23:52 -0700396 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
397 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700398 mHandler = new InternalHandler(handlerThread.getLooper());
399 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700400
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700401 if (netFactory == null) {
402 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
403 }
404
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800405 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800406 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
407 String id = Settings.Secure.getString(context.getContentResolver(),
408 Settings.Secure.ANDROID_ID);
409 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700410 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800411 SystemProperties.set("net.hostname", name);
412 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800413 }
414
Robert Greenwalt94daa182010-09-01 11:34:05 -0700415 // read our default dns server ip
Jeff Sharkey8c870452012-09-26 22:03:49 -0700416 String dns = Settings.Global.getString(context.getContentResolver(),
417 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700418 if (dns == null || dns.length() == 0) {
419 dns = context.getResources().getString(
420 com.android.internal.R.string.config_default_dns_server);
421 }
422 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800423 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
424 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800425 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700426 }
427
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700428 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700429 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700430 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700431 mKeyStore = KeyStore.getInstance();
Wink Saville32506bc2013-06-29 21:10:57 -0700432 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700433
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700434 try {
435 mPolicyManager.registerListener(mPolicyListener);
436 } catch (RemoteException e) {
437 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700438 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700439 }
440
441 final PowerManager powerManager = (PowerManager) context.getSystemService(
442 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700443 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
444 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
445 com.android.internal.R.integer.config_networkTransitionTimeout);
446
Robert Greenwalt2034b912009-08-12 16:08:25 -0700447 mNetTrackers = new NetworkStateTracker[
448 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700449 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700450
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700451 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700452 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700453
Robert Greenwalt2034b912009-08-12 16:08:25 -0700454 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700455 String[] raStrings = context.getResources().getStringArray(
456 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700457 for (String raString : raStrings) {
458 RadioAttributes r = new RadioAttributes(raString);
459 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800460 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700461 continue;
462 }
463 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800464 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700465 r.mType);
466 continue;
467 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700468 mRadioAttributes[r.mType] = r;
469 }
470
Wink Saville00fe5092013-04-23 14:26:51 -0700471 // TODO: What is the "correct" way to do determine if this is a wifi only device?
472 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
473 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700474 String[] naStrings = context.getResources().getStringArray(
475 com.android.internal.R.array.networkAttributes);
476 for (String naString : naStrings) {
477 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700478 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700479 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800480 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700481 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700482 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700483 }
Wink Saville00fe5092013-04-23 14:26:51 -0700484 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
485 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
486 n.type);
487 continue;
488 }
Wink Savillef2a62832011-04-07 14:23:45 -0700489 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800490 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700491 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700492 continue;
493 }
Wink Savillef2a62832011-04-07 14:23:45 -0700494 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800495 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700496 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700497 continue;
498 }
Wink Savillef2a62832011-04-07 14:23:45 -0700499 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700500 mNetworksDefined++;
501 } catch(Exception e) {
502 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700503 }
504 }
505
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700506 mProtectedNetworks = new ArrayList<Integer>();
507 int[] protectedNetworks = context.getResources().getIntArray(
508 com.android.internal.R.array.config_protectedNetworks);
509 for (int p : protectedNetworks) {
510 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
511 mProtectedNetworks.add(p);
512 } else {
513 if (DBG) loge("Ignoring protectedNetwork " + p);
514 }
515 }
516
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700517 // high priority first
518 mPriorityList = new int[mNetworksDefined];
519 {
520 int insertionPoint = mNetworksDefined-1;
521 int currentLowest = 0;
522 int nextLowest = 0;
523 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700524 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700525 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700526 if (na.priority < currentLowest) continue;
527 if (na.priority > currentLowest) {
528 if (na.priority < nextLowest || nextLowest == 0) {
529 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700530 }
531 continue;
532 }
Wink Savillef2a62832011-04-07 14:23:45 -0700533 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700534 }
535 currentLowest = nextLowest;
536 nextLowest = 0;
537 }
538 }
539
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800540 // Update mNetworkPreference according to user mannually first then overlay config.xml
541 mNetworkPreference = getPersistedNetworkPreference();
542 if (mNetworkPreference == -1) {
543 for (int n : mPriorityList) {
544 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
545 mNetworkPreference = n;
546 break;
547 }
548 }
549 if (mNetworkPreference == -1) {
550 throw new IllegalStateException(
551 "You should set at least one default Network in config.xml!");
552 }
553 }
554
Mattias Falkd697aa22011-08-23 14:15:13 +0200555 mNetRequestersPids =
556 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700557 for (int i : mPriorityList) {
Mattias Falkd697aa22011-08-23 14:15:13 +0200558 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700559 }
560
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500561 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700562
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700563 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
564 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700565
566 // Create and start trackers for hard-coded networks
567 for (int targetNetworkType : mPriorityList) {
568 final NetworkConfig config = mNetConfigs[targetNetworkType];
569 final NetworkStateTracker tracker;
570 try {
571 tracker = netFactory.createTracker(targetNetworkType, config);
572 mNetTrackers[targetNetworkType] = tracker;
573 } catch (IllegalArgumentException e) {
574 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
575 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700576 continue;
577 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700578
579 tracker.startMonitoring(context, mTrackerHandler);
580 if (config.isDefault()) {
581 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800582 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700583 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800584
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700585 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700586 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700587 mTethering.getTetherableWifiRegexs().length != 0 ||
588 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700589 mTethering.getUpstreamIfaceTypes().length != 0);
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700590 //set up the listener for user state for creating user VPNs
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800591
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700592 IntentFilter intentFilter = new IntentFilter();
593 intentFilter.addAction(Intent.ACTION_USER_STARTING);
594 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
595 mContext.registerReceiverAsUser(
596 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900597 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
598
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700599 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700600 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700601 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900602 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700603 } catch (RemoteException e) {
604 loge("Error registering observer :" + e);
605 }
606
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700607 if (DBG) {
608 mInetLog = new ArrayList();
609 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700610
611 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
612 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800613
Irfan Sheriff32bed2c2012-09-20 09:32:41 -0700614 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800615 loadGlobalProxy();
John Spurlock1f5cec72013-06-24 14:20:23 -0400616
617 mDataConnectionStats = new DataConnectionStats(mContext);
618 mDataConnectionStats.startMonitoring();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800619 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700620
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700621 /**
622 * Factory that creates {@link NetworkStateTracker} instances using given
623 * {@link NetworkConfig}.
624 */
625 public interface NetworkFactory {
626 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
627 }
628
629 private static class DefaultNetworkFactory implements NetworkFactory {
630 private final Context mContext;
631 private final Handler mTrackerHandler;
632
633 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
634 mContext = context;
635 mTrackerHandler = trackerHandler;
636 }
637
638 @Override
639 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
640 switch (config.radio) {
641 case TYPE_WIFI:
642 return new WifiStateTracker(targetNetworkType, config.name);
643 case TYPE_MOBILE:
644 return new MobileDataStateTracker(targetNetworkType, config.name);
645 case TYPE_DUMMY:
646 return new DummyDataStateTracker(targetNetworkType, config.name);
647 case TYPE_BLUETOOTH:
648 return BluetoothTetheringDataTracker.getInstance();
649 case TYPE_WIMAX:
650 return makeWimaxStateTracker(mContext, mTrackerHandler);
651 case TYPE_ETHERNET:
652 return EthernetDataTracker.getInstance();
653 default:
654 throw new IllegalArgumentException(
655 "Trying to create a NetworkStateTracker for an unknown radio type: "
656 + config.radio);
657 }
658 }
659 }
660
661 /**
662 * Loads external WiMAX library and registers as system service, returning a
663 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
664 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
665 */
666 private static NetworkStateTracker makeWimaxStateTracker(
667 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700668 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900669 DexClassLoader wimaxClassLoader;
670 Class wimaxStateTrackerClass = null;
671 Class wimaxServiceClass = null;
672 Class wimaxManagerClass;
673 String wimaxJarLocation;
674 String wimaxLibLocation;
675 String wimaxManagerClassName;
676 String wimaxServiceClassName;
677 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800678
tk.mun093f55c2011-10-13 22:51:57 +0900679 NetworkStateTracker wimaxStateTracker = null;
680
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700681 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900682 com.android.internal.R.bool.config_wimaxEnabled);
683
684 if (isWimaxEnabled) {
685 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700686 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900687 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700688 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900689 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700690 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900691 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700692 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900693 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700694 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900695 com.android.internal.R.string.config_wimaxStateTrackerClassname);
696
Dianne Hackborndc456a62012-11-08 11:12:09 -0800697 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900698 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700699 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900700 wimaxLibLocation, ClassLoader.getSystemClassLoader());
701
702 try {
703 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
704 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
705 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
706 } catch (ClassNotFoundException ex) {
707 loge("Exception finding Wimax classes: " + ex.toString());
708 return null;
709 }
710 } catch(Resources.NotFoundException ex) {
711 loge("Wimax Resources does not exist!!! ");
712 return null;
713 }
714
715 try {
Dianne Hackborndc456a62012-11-08 11:12:09 -0800716 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900717
718 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
719 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700720 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
721 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900722
723 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
724 (new Class[] {Context.class, wimaxStateTrackerClass});
725 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700726 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900727 wmxSrvConst.setAccessible(false);
728
729 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
730
731 } catch(Exception ex) {
732 loge("Exception creating Wimax classes: " + ex.toString());
733 return null;
734 }
735 } else {
736 loge("Wimax is not enabled or not added to the network attributes!!! ");
737 return null;
738 }
739
740 return wimaxStateTracker;
741 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700742
The Android Open Source Project28527d22009-03-03 19:31:44 -0800743 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700744 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800745 * @param preference the new preference
746 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700747 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800748 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700749
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700750 mHandler.sendMessage(
751 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800752 }
753
754 public int getNetworkPreference() {
755 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700756 int preference;
757 synchronized(this) {
758 preference = mNetworkPreference;
759 }
760 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800761 }
762
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700763 private void handleSetNetworkPreference(int preference) {
764 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700765 mNetConfigs[preference] != null &&
766 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700767 if (mNetworkPreference != preference) {
768 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownc67cf562012-09-25 15:03:20 -0700769 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700770 synchronized(this) {
771 mNetworkPreference = preference;
772 }
773 enforcePreference();
774 }
775 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800776 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700777
Wink Saville4f0de1e2011-08-04 15:01:58 -0700778 private int getConnectivityChangeDelay() {
779 final ContentResolver cr = mContext.getContentResolver();
780
781 /** Check system properties for the default value then use secure settings value, if any. */
782 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey8c870452012-09-26 22:03:49 -0700783 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
784 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
785 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700786 defaultDelay);
787 }
788
The Android Open Source Project28527d22009-03-03 19:31:44 -0800789 private int getPersistedNetworkPreference() {
790 final ContentResolver cr = mContext.getContentResolver();
791
Jeff Brownc67cf562012-09-25 15:03:20 -0700792 final int networkPrefSetting = Settings.Global
793 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800794
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800795 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800796 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700797
The Android Open Source Project28527d22009-03-03 19:31:44 -0800798 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700799 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800800 * In this method, we only tear down a non-preferred network. Establishing
801 * a connection to the preferred network is taken care of when we handle
802 * the disconnect event from the non-preferred network
803 * (see {@link #handleDisconnect(NetworkInfo)}).
804 */
805 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700806 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800807 return;
808
Robert Greenwalt2034b912009-08-12 16:08:25 -0700809 if (!mNetTrackers[mNetworkPreference].isAvailable())
810 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800811
Robert Greenwalt2034b912009-08-12 16:08:25 -0700812 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700813 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700814 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700815 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800816 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700817 " in enforcePreference");
818 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700819 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800820 }
821 }
822 }
823
824 private boolean teardown(NetworkStateTracker netTracker) {
825 if (netTracker.teardown()) {
826 netTracker.setTeardownRequested(true);
827 return true;
828 } else {
829 return false;
830 }
831 }
832
833 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700834 * Check if UID should be blocked from using the network represented by the
835 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700836 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700837 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
838 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700839
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700840 final boolean networkCostly;
841 final int uidRules;
842 synchronized (mRulesLock) {
843 networkCostly = mMeteredIfaces.contains(iface);
844 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700845 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700846
847 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
848 return true;
849 }
850
851 // no restrictive rules; network is visible
852 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700853 }
854
855 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700856 * Return a filtered {@link NetworkInfo}, potentially marked
857 * {@link DetailedState#BLOCKED} based on
858 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700859 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700860 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
861 NetworkInfo info = tracker.getNetworkInfo();
862 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700863 // network is blocked; clone and override state
864 info = new NetworkInfo(info);
865 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700866 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700867 if (mLockdownTracker != null) {
868 info = mLockdownTracker.augmentNetworkInfo(info);
869 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700870 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700871 }
872
873 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800874 * Return NetworkInfo for the active (i.e., connected) network interface.
875 * It is assumed that at most one network is active at a time. If more
876 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700877 * @return the info for the active network, or {@code null} if none is
878 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800879 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700880 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800881 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700882 enforceAccessPermission();
883 final int uid = Binder.getCallingUid();
884 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800885 }
886
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700887 public NetworkInfo getActiveNetworkInfoUnfiltered() {
888 enforceAccessPermission();
889 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
890 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
891 if (tracker != null) {
892 return tracker.getNetworkInfo();
893 }
894 }
895 return null;
896 }
897
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700898 @Override
899 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
900 enforceConnectivityInternalPermission();
901 return getNetworkInfo(mActiveDefaultNetwork, uid);
902 }
903
904 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800905 public NetworkInfo getNetworkInfo(int networkType) {
906 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700907 final int uid = Binder.getCallingUid();
908 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800909 }
910
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700911 private NetworkInfo getNetworkInfo(int networkType, int uid) {
912 NetworkInfo info = null;
913 if (isNetworkTypeValid(networkType)) {
914 final NetworkStateTracker tracker = mNetTrackers[networkType];
915 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700916 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700917 }
918 }
919 return info;
920 }
921
922 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800923 public NetworkInfo[] getAllNetworkInfo() {
924 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700925 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700926 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700927 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700928 for (NetworkStateTracker tracker : mNetTrackers) {
929 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700930 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700931 }
932 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800933 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700934 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800935 }
936
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700937 @Override
938 public boolean isNetworkSupported(int networkType) {
939 enforceAccessPermission();
940 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
941 }
942
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700943 /**
944 * Return LinkProperties for the active (i.e., connected) default
945 * network interface. It is assumed that at most one default network
946 * is active at a time. If more than one is active, it is indeterminate
947 * which will be returned.
948 * @return the ip properties for the active network, or {@code null} if
949 * none is active
950 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700951 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700952 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700953 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700954 }
955
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700956 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700957 public LinkProperties getLinkProperties(int networkType) {
958 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700959 if (isNetworkTypeValid(networkType)) {
960 final NetworkStateTracker tracker = mNetTrackers[networkType];
961 if (tracker != null) {
962 return tracker.getLinkProperties();
963 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700964 }
965 return null;
966 }
967
Jeff Sharkey21062e72011-05-28 20:56:34 -0700968 @Override
969 public NetworkState[] getAllNetworkState() {
970 enforceAccessPermission();
971 final int uid = Binder.getCallingUid();
972 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700973 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700974 for (NetworkStateTracker tracker : mNetTrackers) {
975 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700976 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700977 result.add(new NetworkState(
978 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
979 }
980 }
981 }
982 return result.toArray(new NetworkState[result.size()]);
983 }
984
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700985 private NetworkState getNetworkStateUnchecked(int networkType) {
986 if (isNetworkTypeValid(networkType)) {
987 final NetworkStateTracker tracker = mNetTrackers[networkType];
988 if (tracker != null) {
989 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
990 tracker.getLinkCapabilities());
991 }
992 }
993 return null;
994 }
995
996 @Override
997 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
998 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700999
1000 final long token = Binder.clearCallingIdentity();
1001 try {
1002 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1003 if (state != null) {
1004 try {
1005 return mPolicyManager.getNetworkQuotaInfo(state);
1006 } catch (RemoteException e) {
1007 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001008 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001009 return null;
1010 } finally {
1011 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001012 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001013 }
1014
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001015 @Override
1016 public boolean isActiveNetworkMetered() {
1017 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001018 final long token = Binder.clearCallingIdentity();
1019 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001020 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001021 } finally {
1022 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001023 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001024 }
1025
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001026 private boolean isNetworkMeteredUnchecked(int networkType) {
1027 final NetworkState state = getNetworkStateUnchecked(networkType);
1028 if (state != null) {
1029 try {
1030 return mPolicyManager.isNetworkMetered(state);
1031 } catch (RemoteException e) {
1032 }
1033 }
1034 return false;
1035 }
1036
The Android Open Source Project28527d22009-03-03 19:31:44 -08001037 public boolean setRadios(boolean turnOn) {
1038 boolean result = true;
1039 enforceChangePermission();
1040 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001041 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001042 }
1043 return result;
1044 }
1045
1046 public boolean setRadio(int netType, boolean turnOn) {
1047 enforceChangePermission();
1048 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1049 return false;
1050 }
1051 NetworkStateTracker tracker = mNetTrackers[netType];
1052 return tracker != null && tracker.setRadio(turnOn);
1053 }
1054
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001055 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1056 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001057 public void interfaceClassDataActivityChanged(String label, boolean active) {
1058 int deviceType = Integer.parseInt(label);
1059 sendDataActivityBroadcast(deviceType, active);
1060 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001061 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001062
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001063 /**
1064 * Used to notice when the calling process dies so we can self-expire
1065 *
1066 * Also used to know if the process has cleaned up after itself when
1067 * our auto-expire timer goes off. The timer has a link to an object.
1068 *
1069 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001070 private class FeatureUser implements IBinder.DeathRecipient {
1071 int mNetworkType;
1072 String mFeature;
1073 IBinder mBinder;
1074 int mPid;
1075 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001076 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001077
1078 FeatureUser(int type, String feature, IBinder binder) {
1079 super();
1080 mNetworkType = type;
1081 mFeature = feature;
1082 mBinder = binder;
1083 mPid = getCallingPid();
1084 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001085 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001086
Robert Greenwalt2034b912009-08-12 16:08:25 -07001087 try {
1088 mBinder.linkToDeath(this, 0);
1089 } catch (RemoteException e) {
1090 binderDied();
1091 }
1092 }
1093
1094 void unlinkDeathRecipient() {
1095 mBinder.unlinkToDeath(this, 0);
1096 }
1097
1098 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001099 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001100 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1101 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001102 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001103 }
1104
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001105 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001106 if (VDBG) {
1107 log("ConnectivityService FeatureUser expire(" +
1108 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1109 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1110 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001111 stopUsingNetworkFeature(this, false);
1112 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001113
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001114 public boolean isSameUser(FeatureUser u) {
1115 if (u == null) return false;
1116
1117 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1118 }
1119
1120 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1121 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1122 TextUtils.equals(mFeature, feature)) {
1123 return true;
1124 }
1125 return false;
1126 }
1127
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001128 public String toString() {
1129 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1130 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1131 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001132 }
1133
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001134 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001135 public int startUsingNetworkFeature(int networkType, String feature,
1136 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001137 long startTime = 0;
1138 if (DBG) {
1139 startTime = SystemClock.elapsedRealtime();
1140 }
Wink Savillea7d56572011-09-21 11:05:43 -07001141 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001142 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1143 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001144 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001145 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001146 try {
1147 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1148 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001149 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001150 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001151
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001152 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001153
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001154 // TODO - move this into individual networktrackers
1155 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001156
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001157 if (mLockdownEnabled) {
1158 // Since carrier APNs usually aren't available from VPN
1159 // endpoint, mark them as unavailable.
1160 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1161 }
1162
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001163 if (mProtectedNetworks.contains(usedNetworkType)) {
1164 enforceConnectivityInternalPermission();
1165 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001166
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001167 // if UID is restricted, don't allow them to bring up metered APNs
1168 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1169 final int uidRules;
1170 synchronized (mRulesLock) {
1171 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1172 }
1173 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001174 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001175 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001176
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001177 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1178 if (network != null) {
1179 Integer currentPid = new Integer(getCallingPid());
1180 if (usedNetworkType != networkType) {
1181 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001182
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001183 if (ni.isAvailable() == false) {
1184 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1185 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001186 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001187 } else {
1188 // else make the attempt anyway - probably giving REQUEST_STARTED below
1189 if (DBG) {
1190 log("special network not available, but try anyway ni=" +
1191 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001192 }
1193 }
1194 }
1195
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001196 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001197
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001198 synchronized(this) {
1199 boolean addToList = true;
1200 if (restoreTimer < 0) {
1201 // In case there is no timer is specified for the feature,
1202 // make sure we don't add duplicate entry with the same request.
1203 for (FeatureUser u : mFeatureUsers) {
1204 if (u.isSameUser(f)) {
1205 // Duplicate user is found. Do not add.
1206 addToList = false;
1207 break;
1208 }
1209 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001210 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001211
1212 if (addToList) mFeatureUsers.add(f);
1213 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1214 // this gets used for per-pid dns when connected
1215 mNetRequestersPids[usedNetworkType].add(currentPid);
1216 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001217 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001218
1219 if (restoreTimer >= 0) {
1220 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1221 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1222 }
1223
1224 if ((ni.isConnectedOrConnecting() == true) &&
1225 !network.isTeardownRequested()) {
1226 if (ni.isConnected() == true) {
1227 final long token = Binder.clearCallingIdentity();
1228 try {
1229 // add the pid-specific dns
1230 handleDnsConfigurationChange(usedNetworkType);
1231 if (VDBG) log("special network already active");
1232 } finally {
1233 Binder.restoreCallingIdentity(token);
1234 }
Wink Saville64e3f782012-07-10 12:37:54 -07001235 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001236 }
1237 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001238 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001239 }
1240
1241 // check if the radio in play can make another contact
1242 // assume if cannot for now
1243
1244 if (DBG) {
1245 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1246 feature);
1247 }
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001248 if (network.reconnect()) {
1249 return PhoneConstants.APN_REQUEST_STARTED;
1250 } else {
1251 return PhoneConstants.APN_REQUEST_FAILED;
1252 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001253 } else {
1254 // need to remember this unsupported request so we respond appropriately on stop
1255 synchronized(this) {
1256 mFeatureUsers.add(f);
1257 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1258 // this gets used for per-pid dns when connected
1259 mNetRequestersPids[usedNetworkType].add(currentPid);
1260 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001261 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001262 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001263 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001264 }
Wink Saville64e3f782012-07-10 12:37:54 -07001265 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001266 } finally {
1267 if (DBG) {
1268 final long execTime = SystemClock.elapsedRealtime() - startTime;
1269 if (execTime > 250) {
1270 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1271 } else {
1272 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1273 }
1274 }
1275 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001276 }
1277
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001278 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001279 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001280 enforceChangePermission();
1281
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001282 int pid = getCallingPid();
1283 int uid = getCallingUid();
1284
1285 FeatureUser u = null;
1286 boolean found = false;
1287
1288 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001289 for (FeatureUser x : mFeatureUsers) {
1290 if (x.isSameUser(pid, uid, networkType, feature)) {
1291 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001292 found = true;
1293 break;
1294 }
1295 }
1296 }
1297 if (found && u != null) {
1298 // stop regardless of how many other time this proc had called start
1299 return stopUsingNetworkFeature(u, true);
1300 } else {
1301 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001302 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001303 return 1;
1304 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001305 }
1306
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001307 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1308 int networkType = u.mNetworkType;
1309 String feature = u.mFeature;
1310 int pid = u.mPid;
1311 int uid = u.mUid;
1312
1313 NetworkStateTracker tracker = null;
1314 boolean callTeardown = false; // used to carry our decision outside of sync block
1315
Wink Savillea7d56572011-09-21 11:05:43 -07001316 if (VDBG) {
1317 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001318 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001319
The Android Open Source Project28527d22009-03-03 19:31:44 -08001320 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001321 if (DBG) {
1322 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1323 ", net is invalid");
1324 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001325 return -1;
1326 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001327
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001328 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1329 // sync block
1330 synchronized(this) {
1331 // check if this process still has an outstanding start request
1332 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001333 if (VDBG) {
1334 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1335 ", ignoring");
1336 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001337 return 1;
1338 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001339 u.unlinkDeathRecipient();
1340 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1341 // If we care about duplicate requests, check for that here.
1342 //
1343 // This is done to support the extension of a request - the app
1344 // can request we start the network feature again and renew the
1345 // auto-shutoff delay. Normal "stop" calls from the app though
1346 // do not pay attention to duplicate requests - in effect the
1347 // API does not refcount and a single stop will counter multiple starts.
1348 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001349 for (FeatureUser x : mFeatureUsers) {
1350 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001351 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001352 return 1;
1353 }
1354 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001355 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001356
repo syncf5de5572011-07-29 23:55:49 -07001357 // TODO - move to individual network trackers
1358 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1359
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001360 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001361 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001362 if (DBG) {
1363 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1364 " no known tracker for used net type " + usedNetworkType);
1365 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001366 return -1;
1367 }
1368 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001369 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001370 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalte767d812013-02-12 17:18:25 -08001371
1372 final long token = Binder.clearCallingIdentity();
1373 try {
1374 reassessPidDns(pid, true);
1375 } finally {
1376 Binder.restoreCallingIdentity(token);
1377 }
Mattias Falkd697aa22011-08-23 14:15:13 +02001378 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001379 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001380 if (VDBG) {
1381 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1382 " others still using it");
1383 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001384 return 1;
1385 }
1386 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001387 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001388 if (DBG) {
1389 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1390 " not a known feature - dropping");
1391 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001392 }
1393 }
Wink Savillea7d56572011-09-21 11:05:43 -07001394
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001395 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001396 if (DBG) {
1397 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1398 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001399 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001400 return 1;
1401 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001402 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001403 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001404 }
1405
1406 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001407 * @deprecated use requestRouteToHostAddress instead
1408 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001409 * Ensure that a network route exists to deliver traffic to the specified
1410 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001411 * @param networkType the type of the network over which traffic to the
1412 * specified host is to be routed
1413 * @param hostAddress the IP address of the host to which the route is
1414 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001415 * @return {@code true} on success, {@code false} on failure
1416 */
1417 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001418 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1419
1420 if (inetAddress == null) {
1421 return false;
1422 }
1423
1424 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1425 }
1426
1427 /**
1428 * Ensure that a network route exists to deliver traffic to the specified
1429 * host via the specified network interface.
1430 * @param networkType the type of the network over which traffic to the
1431 * specified host is to be routed
1432 * @param hostAddress the IP address of the host to which the route is
1433 * desired
1434 * @return {@code true} on success, {@code false} on failure
1435 */
1436 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001437 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001438 if (mProtectedNetworks.contains(networkType)) {
1439 enforceConnectivityInternalPermission();
1440 }
1441
The Android Open Source Project28527d22009-03-03 19:31:44 -08001442 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001443 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001444 return false;
1445 }
1446 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001447 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001448
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001449 if (tracker == null || (netState != DetailedState.CONNECTED &&
1450 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001451 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001452 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07001453 log("requestRouteToHostAddress on down network "
1454 + "(" + networkType + ") - dropped"
1455 + " tracker=" + tracker
1456 + " netState=" + netState
1457 + " isTeardownRequested="
1458 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001459 }
1460 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001461 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001462 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001463 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001464 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001465 LinkProperties lp = tracker.getLinkProperties();
Wink Saville32506bc2013-06-29 21:10:57 -07001466 boolean ok = addRouteToAddress(lp, addr);
1467 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1468 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001469 } catch (UnknownHostException e) {
1470 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1471 } finally {
1472 Binder.restoreCallingIdentity(token);
1473 }
Wink Saville32506bc2013-06-29 21:10:57 -07001474 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001475 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001476 }
1477
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001478 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001479 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001480 }
1481
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001482 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001483 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001484 }
1485
Robert Greenwalt98107422011-07-22 11:55:33 -07001486 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001487 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001488 }
1489
1490 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001491 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001492 }
1493
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001494 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1495 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001496 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001497 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001498 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001499 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001500 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001501 if (bestRoute.getGateway().equals(addr)) {
1502 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001503 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001504 } else {
1505 // if we will connect to this through another route, add a direct route
1506 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001507 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001508 }
1509 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001510 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001511 }
1512
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001513 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1514 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001515 if ((lp == null) || (r == null)) {
1516 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001517 return false;
1518 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001519
1520 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001521 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001522 return false;
1523 }
1524
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001525 String ifaceName = r.getInterface();
1526 if(ifaceName == null) {
1527 loge("Error modifying route - no interface name");
1528 return false;
1529 }
Robert Greenwalt59070cf2013-04-11 13:48:16 -07001530 if (r.hasGateway()) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001531 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001532 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001533 if (bestRoute.getGateway().equals(r.getGateway())) {
1534 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001535 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001536 } else {
1537 // if we will connect to our gateway through another route, add a direct
1538 // route to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001539 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1540 bestRoute.getGateway(),
1541 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001542 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001543 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001544 }
1545 }
1546 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001547 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001548 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001549 if (toDefaultTable) {
1550 mAddedRoutes.add(r); // only track default table - only one apps can effect
1551 mNetd.addRoute(ifaceName, r);
1552 } else {
1553 mNetd.addSecondaryRoute(ifaceName, r);
1554 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001555 } catch (Exception e) {
1556 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001557 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001558 return false;
1559 }
1560 } else {
1561 // if we remove this one and there are no more like it, then refcount==0 and
1562 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001563 if (toDefaultTable) {
1564 mAddedRoutes.remove(r);
1565 if (mAddedRoutes.contains(r) == false) {
1566 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1567 try {
1568 mNetd.removeRoute(ifaceName, r);
1569 } catch (Exception e) {
1570 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001571 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001572 return false;
1573 }
1574 } else {
1575 if (VDBG) log("not removing " + r + " as it's still in use");
1576 }
1577 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001578 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001579 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001580 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001581 } catch (Exception e) {
1582 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001583 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001584 return false;
1585 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001586 }
1587 }
1588 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001589 }
1590
1591 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001592 * @see ConnectivityManager#getMobileDataEnabled()
1593 */
1594 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001595 // TODO: This detail should probably be in DataConnectionTracker's
1596 // which is where we store the value and maybe make this
1597 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001598 enforceAccessPermission();
Jeff Sharkey8b361572012-09-26 15:54:06 -07001599 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1600 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001601 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001602 return retVal;
1603 }
1604
Robert Greenwalt34848c02011-03-25 13:09:25 -07001605 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001606 enforceConnectivityInternalPermission();
1607
Robert Greenwalt34848c02011-03-25 13:09:25 -07001608 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1609 (met ? ENABLED : DISABLED), networkType));
1610 }
1611
1612 private void handleSetDependencyMet(int networkType, boolean met) {
1613 if (mNetTrackers[networkType] != null) {
1614 if (DBG) {
1615 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1616 }
1617 mNetTrackers[networkType].setDependencyMet(met);
1618 }
1619 }
1620
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001621 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1622 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001623 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001624 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001625 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001626 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001627 }
1628
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001629 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001630 // skip update when we've already applied rules
1631 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1632 if (oldRules == uidRules) return;
1633
1634 mUidRules.put(uid, uidRules);
1635 }
1636
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001637 // TODO: notify UID when it has requested targeted updates
1638 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001639
1640 @Override
1641 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001642 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001643 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001644 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001645 }
1646
1647 synchronized (mRulesLock) {
1648 mMeteredIfaces.clear();
1649 for (String iface : meteredIfaces) {
1650 mMeteredIfaces.add(iface);
1651 }
1652 }
1653 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001654
1655 @Override
1656 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1657 // caller is NPMS, since we only register with them
1658 if (LOGD_RULES) {
1659 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1660 }
1661
1662 // kick off connectivity change broadcast for active network, since
1663 // global background policy change is radical.
1664 final int networkType = mActiveDefaultNetwork;
1665 if (isNetworkTypeValid(networkType)) {
1666 final NetworkStateTracker tracker = mNetTrackers[networkType];
1667 if (tracker != null) {
1668 final NetworkInfo info = tracker.getNetworkInfo();
1669 if (info != null && info.isConnected()) {
1670 sendConnectedBroadcast(info);
1671 }
1672 }
1673 }
1674 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001675 };
1676
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001677 /**
1678 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1679 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001680 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001681 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001682 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001683
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001684 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001685 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001686 }
1687
1688 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001689 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001690 if (VDBG) {
1691 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001692 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001693 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1694 }
tk.mun5eee1042012-01-06 10:43:52 +09001695 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1696 if (VDBG) {
1697 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1698 }
1699 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1700 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001701 }
1702
1703 @Override
1704 public void setPolicyDataEnable(int networkType, boolean enabled) {
1705 // only someone like NPMS should only be calling us
1706 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1707
1708 mHandler.sendMessage(mHandler.obtainMessage(
1709 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1710 }
1711
1712 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1713 if (isNetworkTypeValid(networkType)) {
1714 final NetworkStateTracker tracker = mNetTrackers[networkType];
1715 if (tracker != null) {
1716 tracker.setPolicyDataEnable(enabled);
1717 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001718 }
1719 }
1720
The Android Open Source Project28527d22009-03-03 19:31:44 -08001721 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001722 mContext.enforceCallingOrSelfPermission(
1723 android.Manifest.permission.ACCESS_NETWORK_STATE,
1724 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001725 }
1726
1727 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001728 mContext.enforceCallingOrSelfPermission(
1729 android.Manifest.permission.CHANGE_NETWORK_STATE,
1730 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001731 }
1732
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001733 // TODO Make this a special check when it goes public
1734 private void enforceTetherChangePermission() {
1735 mContext.enforceCallingOrSelfPermission(
1736 android.Manifest.permission.CHANGE_NETWORK_STATE,
1737 "ConnectivityService");
1738 }
1739
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001740 private void enforceTetherAccessPermission() {
1741 mContext.enforceCallingOrSelfPermission(
1742 android.Manifest.permission.ACCESS_NETWORK_STATE,
1743 "ConnectivityService");
1744 }
1745
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001746 private void enforceConnectivityInternalPermission() {
1747 mContext.enforceCallingOrSelfPermission(
1748 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1749 "ConnectivityService");
1750 }
1751
Chad Brubaker11f22252013-07-11 13:29:30 -07001752 private void enforceMarkNetworkSocketPermission() {
1753 //Media server special case
1754 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1755 return;
1756 }
1757 mContext.enforceCallingOrSelfPermission(
1758 android.Manifest.permission.MARK_NETWORK_SOCKET,
1759 "ConnectivityService");
1760 }
1761
The Android Open Source Project28527d22009-03-03 19:31:44 -08001762 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001763 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1764 * network, we ignore it. If it is for the active network, we send out a
1765 * broadcast. But first, we check whether it might be possible to connect
1766 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001767 * @param info the {@code NetworkInfo} for the network
1768 */
1769 private void handleDisconnect(NetworkInfo info) {
1770
Robert Greenwalt2034b912009-08-12 16:08:25 -07001771 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001772
Robert Greenwalt2034b912009-08-12 16:08:25 -07001773 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Baie2462442012-06-28 15:26:19 -07001774
1775 // Remove idletimer previously setup in {@code handleConnect}
1776 removeDataActivityTracking(prevNetType);
1777
The Android Open Source Project28527d22009-03-03 19:31:44 -08001778 /*
1779 * If the disconnected network is not the active one, then don't report
1780 * this as a loss of connectivity. What probably happened is that we're
1781 * getting the disconnect for a network that we explicitly disabled
1782 * in accordance with network preference policies.
1783 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001784 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkd697aa22011-08-23 14:15:13 +02001785 List<Integer> pids = mNetRequestersPids[prevNetType];
1786 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001787 // will remove them because the net's no longer connected
1788 // need to do this now as only now do we know the pids and
1789 // can properly null things that are no longer referenced.
1790 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001791 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001792 }
1793
The Android Open Source Project28527d22009-03-03 19:31:44 -08001794 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001795 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001796 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001797 if (info.isFailover()) {
1798 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1799 info.setFailover(false);
1800 }
1801 if (info.getReason() != null) {
1802 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1803 }
1804 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001805 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1806 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001807 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001808
Robert Greenwalt34848c02011-03-25 13:09:25 -07001809 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001810 tryFailover(prevNetType);
1811 if (mActiveDefaultNetwork != -1) {
1812 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001813 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1814 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001815 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001816 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1817 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001818 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001819 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001820
1821 // Reset interface if no other connections are using the same interface
1822 boolean doReset = true;
1823 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1824 if (linkProperties != null) {
1825 String oldIface = linkProperties.getInterfaceName();
1826 if (TextUtils.isEmpty(oldIface) == false) {
1827 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1828 if (networkStateTracker == null) continue;
1829 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1830 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1831 LinkProperties l = networkStateTracker.getLinkProperties();
1832 if (l == null) continue;
1833 if (oldIface.equals(l.getInterfaceName())) {
1834 doReset = false;
1835 break;
1836 }
1837 }
1838 }
1839 }
1840 }
1841
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001842 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001843 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001844
Jeff Sharkey971cd162011-08-29 16:02:57 -07001845 final Intent immediateIntent = new Intent(intent);
1846 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1847 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001848 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001849 /*
1850 * If the failover network is already connected, then immediately send
1851 * out a followup broadcast indicating successful failover
1852 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001853 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001854 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1855 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001856 }
1857 }
1858
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001859 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001860 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001861 * If this is a default network, check if other defaults are available.
1862 * Try to reconnect on all available and let them hash it out when
1863 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001864 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001865 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001866 if (mActiveDefaultNetwork == prevNetType) {
1867 mActiveDefaultNetwork = -1;
1868 }
1869
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001870 // don't signal a reconnect for anything lower or equal priority than our
1871 // current connected default
1872 // TODO - don't filter by priority now - nice optimization but risky
1873// int currentPriority = -1;
1874// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001875// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001876// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001877 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001878 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001879 if (mNetConfigs[checkType] == null) continue;
1880 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001881 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001882
1883// Enabling the isAvailable() optimization caused mobile to not get
1884// selected if it was in the middle of error handling. Specifically
1885// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1886// would not be available and we wouldn't get connected to anything.
1887// So removing the isAvailable() optimization below for now. TODO: This
1888// optimization should work and we need to investigate why it doesn't work.
1889// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1890// complete before it is really complete.
1891// if (!mNetTrackers[checkType].isAvailable()) continue;
1892
Robert Greenwalt34848c02011-03-25 13:09:25 -07001893// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001894
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001895 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1896 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1897 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1898 checkInfo.setFailover(true);
1899 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001900 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001901 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001902 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001903 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001904 }
1905
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001906 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001907 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07001908 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1909 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001910 }
1911
Wink Saville4f0de1e2011-08-04 15:01:58 -07001912 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001913 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1914 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001915 }
1916
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001917 private void sendInetConditionBroadcast(NetworkInfo info) {
1918 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1919 }
1920
Wink Saville4f0de1e2011-08-04 15:01:58 -07001921 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001922 if (mLockdownTracker != null) {
1923 info = mLockdownTracker.augmentNetworkInfo(info);
1924 }
1925
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001926 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001927 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001928 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001929 if (info.isFailover()) {
1930 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1931 info.setFailover(false);
1932 }
1933 if (info.getReason() != null) {
1934 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1935 }
1936 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001937 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1938 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001939 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001940 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001941 return intent;
1942 }
1943
1944 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1945 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1946 }
1947
1948 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1949 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001950 }
1951
Haoyu Baib5da5752012-06-20 14:29:57 -07001952 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1953 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1954 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1955 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborne588ca12012-09-04 18:48:37 -07001956 final long ident = Binder.clearCallingIdentity();
1957 try {
1958 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1959 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1960 } finally {
1961 Binder.restoreCallingIdentity(ident);
1962 }
Haoyu Baib5da5752012-06-20 14:29:57 -07001963 }
1964
The Android Open Source Project28527d22009-03-03 19:31:44 -08001965 /**
1966 * Called when an attempt to fail over to another network has failed.
1967 * @param info the {@link NetworkInfo} for the failed network
1968 */
1969 private void handleConnectionFailure(NetworkInfo info) {
1970 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001971
Robert Greenwalt2034b912009-08-12 16:08:25 -07001972 String reason = info.getReason();
1973 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001974
Robert Greenwalte981bc52010-10-08 16:35:52 -07001975 String reasonText;
1976 if (reason == null) {
1977 reasonText = ".";
1978 } else {
1979 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001980 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001981 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001982
1983 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001984 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001985 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001986 if (getActiveNetworkInfo() == null) {
1987 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1988 }
1989 if (reason != null) {
1990 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1991 }
1992 if (extraInfo != null) {
1993 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1994 }
1995 if (info.isFailover()) {
1996 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1997 info.setFailover(false);
1998 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001999
Robert Greenwalt34848c02011-03-25 13:09:25 -07002000 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002001 tryFailover(info.getType());
2002 if (mActiveDefaultNetwork != -1) {
2003 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002004 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2005 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002006 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002007 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2008 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002009 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002010
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002011 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002012
2013 final Intent immediateIntent = new Intent(intent);
2014 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2015 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002016 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002017 /*
2018 * If the failover network is already connected, then immediately send
2019 * out a followup broadcast indicating successful failover
2020 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002021 if (mActiveDefaultNetwork != -1) {
2022 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002023 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002024 }
2025
2026 private void sendStickyBroadcast(Intent intent) {
2027 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002028 if (!mSystemReady) {
2029 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002030 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002031 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002032 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002033 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002034 }
2035
Dianne Hackborne588ca12012-09-04 18:48:37 -07002036 final long ident = Binder.clearCallingIdentity();
2037 try {
2038 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2039 } finally {
2040 Binder.restoreCallingIdentity(ident);
2041 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002042 }
2043 }
2044
Wink Saville4f0de1e2011-08-04 15:01:58 -07002045 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2046 if (delayMs <= 0) {
2047 sendStickyBroadcast(intent);
2048 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002049 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002050 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2051 + intent.getAction());
2052 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002053 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2054 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2055 }
2056 }
2057
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002058 void systemReady() {
2059 synchronized(this) {
2060 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002061 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002062 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002063 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002064 }
2065 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002066 // load the global proxy at startup
2067 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002068
2069 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2070 // for user to unlock device.
2071 if (!updateLockdownVpn()) {
2072 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2073 mContext.registerReceiver(mUserPresentReceiver, filter);
2074 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002075 }
2076
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002077 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2078 @Override
2079 public void onReceive(Context context, Intent intent) {
2080 // Try creating lockdown tracker, since user present usually means
2081 // unlocked keystore.
2082 if (updateLockdownVpn()) {
2083 mContext.unregisterReceiver(this);
2084 }
2085 }
2086 };
2087
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002088 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2089 if ((type != mNetworkPreference &&
2090 mNetConfigs[mActiveDefaultNetwork].priority >
2091 mNetConfigs[type].priority) ||
2092 mNetworkPreference == mActiveDefaultNetwork) return false;
2093 return true;
2094 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002095
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002096 private void handleConnect(NetworkInfo info) {
2097 final int newNetType = info.getType();
2098
2099 setupDataActivityTracking(newNetType);
Haoyu Baie2462442012-06-28 15:26:19 -07002100
The Android Open Source Project28527d22009-03-03 19:31:44 -08002101 // snapshot isFailover, because sendConnectedBroadcast() resets it
2102 boolean isFailover = info.isFailover();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002103 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002104 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002105
Robert Greenwalt2034b912009-08-12 16:08:25 -07002106 // if this is a default net and other default is running
2107 // kill the one not preferred
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002108 if (mNetConfigs[newNetType].isDefault()) {
2109 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2110 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002111 // tear down the other
2112 NetworkStateTracker otherNet =
2113 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002114 if (DBG) {
2115 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002116 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002117 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002118 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002119 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002120 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002121 return;
2122 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002123 } else {
2124 // don't accept this one
2125 if (VDBG) {
2126 log("Not broadcasting CONNECT_ACTION " +
2127 "to torn down network " + info.getTypeName());
2128 }
2129 teardown(thisNet);
2130 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002131 }
2132 }
2133 synchronized (ConnectivityService.this) {
2134 // have a new default network, release the transition wakelock in a second
2135 // if it's held. The second pause is to allow apps to reconnect over the
2136 // new network
2137 if (mNetTransitionWakeLock.isHeld()) {
2138 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002139 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002140 mNetTransitionWakeLockSerialNumber, 0),
2141 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002142 }
2143 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002144 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002145 // this will cause us to come up initially as unconnected and switching
2146 // to connected after our normal pause unless somebody reports us as reall
2147 // disconnected
2148 mDefaultInetConditionPublished = 0;
2149 mDefaultConnectionSequence++;
2150 mInetConditionChangeInFlight = false;
2151 // Don't do this - if we never sign in stay, grey
2152 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002153 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002154 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002155 updateNetworkSettings(thisNet);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002156 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002157 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002158
2159 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002160 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002161 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002162 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002163 } catch (RemoteException e) {
2164 // ignored; service lives in system_server
2165 }
2166 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002167 }
2168
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002169 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2170 if (DBG) log("Captive portal check " + info);
2171 int type = info.getType();
2172 final NetworkStateTracker thisNet = mNetTrackers[type];
2173 if (mNetConfigs[type].isDefault()) {
2174 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2175 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2176 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002177 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002178 return;
2179 } else {
2180 if (DBG) log("Tear down low priority net " + info.getTypeName());
2181 teardown(thisNet);
2182 return;
2183 }
2184 }
2185 }
2186
2187 thisNet.captivePortalCheckComplete();
2188 }
2189
2190 /** @hide */
2191 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002192 enforceConnectivityInternalPermission();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002193 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002194 }
2195
The Android Open Source Project28527d22009-03-03 19:31:44 -08002196 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002197 * Setup data activity tracking for the given network interface.
2198 *
2199 * Every {@code setupDataActivityTracking} should be paired with a
2200 * {@link removeDataActivityTracking} for cleanup.
2201 */
2202 private void setupDataActivityTracking(int type) {
2203 final NetworkStateTracker thisNet = mNetTrackers[type];
2204 final String iface = thisNet.getLinkProperties().getInterfaceName();
2205
2206 final int timeout;
2207
2208 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002209 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2210 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Baie2462442012-06-28 15:26:19 -07002211 0);
2212 // Canonicalize mobile network type
2213 type = ConnectivityManager.TYPE_MOBILE;
2214 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002215 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2216 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Baie2462442012-06-28 15:26:19 -07002217 0);
2218 } else {
2219 // do not track any other networks
2220 timeout = 0;
2221 }
2222
2223 if (timeout > 0 && iface != null) {
2224 try {
2225 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2226 } catch (RemoteException e) {
2227 }
2228 }
2229 }
2230
2231 /**
2232 * Remove data activity tracking when network disconnects.
2233 */
2234 private void removeDataActivityTracking(int type) {
2235 final NetworkStateTracker net = mNetTrackers[type];
2236 final String iface = net.getLinkProperties().getInterfaceName();
2237
2238 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2239 ConnectivityManager.TYPE_WIFI == type)) {
2240 try {
2241 // the call fails silently if no idletimer setup for this interface
2242 mNetd.removeIdleTimer(iface);
2243 } catch (RemoteException e) {
2244 }
2245 }
2246 }
2247
2248 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002249 * After a change in the connectivity state of a network. We're mainly
2250 * concerned with making sure that the list of DNS servers is set up
2251 * according to which networks are connected, and ensuring that the
2252 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002253 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002254 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002255 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2256
The Android Open Source Project28527d22009-03-03 19:31:44 -08002257 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002258 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002259 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002260 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002261 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002262
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002263 LinkProperties curLp = mCurrentLinkProperties[netType];
2264 LinkProperties newLp = null;
2265
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002266 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002267 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002268 if (VDBG) {
2269 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2270 " doReset=" + doReset + " resetMask=" + resetMask +
2271 "\n curLp=" + curLp +
2272 "\n newLp=" + newLp);
2273 }
2274
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002275 if (curLp != null) {
2276 if (curLp.isIdenticalInterfaceName(newLp)) {
2277 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2278 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2279 for (LinkAddress linkAddr : car.removed) {
2280 if (linkAddr.getAddress() instanceof Inet4Address) {
2281 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2282 }
2283 if (linkAddr.getAddress() instanceof Inet6Address) {
2284 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2285 }
Wink Saville051a6642011-07-13 13:44:13 -07002286 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002287 if (DBG) {
2288 log("handleConnectivityChange: addresses changed" +
2289 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2290 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002291 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002292 } else {
2293 if (DBG) {
2294 log("handleConnectivityChange: address are the same reset per doReset" +
2295 " linkProperty[" + netType + "]:" +
2296 " resetMask=" + resetMask);
2297 }
Wink Saville051a6642011-07-13 13:44:13 -07002298 }
2299 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002300 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002301 if (DBG) {
2302 log("handleConnectivityChange: interface not not equivalent reset both" +
2303 " linkProperty[" + netType + "]:" +
2304 " resetMask=" + resetMask);
2305 }
Wink Saville051a6642011-07-13 13:44:13 -07002306 }
Wink Saville051a6642011-07-13 13:44:13 -07002307 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002308 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002309 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002310 }
2311 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002312 if (VDBG) {
2313 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2314 " doReset=" + doReset + " resetMask=" + resetMask +
2315 "\n curLp=" + curLp +
2316 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002317 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002318 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002319 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07002320 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002321
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002322 if (resetMask != 0 || resetDns) {
Robert Greenwalt4398f342013-05-23 18:33:06 -07002323 if (curLp != null) {
2324 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti63839822013-03-20 19:22:58 +09002325 if (TextUtils.isEmpty(iface) == false) {
2326 if (resetMask != 0) {
2327 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2328 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002329
Lorenzo Colitti63839822013-03-20 19:22:58 +09002330 // Tell VPN the interface is down. It is a temporary
2331 // but effective fix to make VPN aware of the change.
2332 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07002333 synchronized(mVpns) {
2334 for (int i = 0; i < mVpns.size(); i++) {
2335 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2336 }
2337 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002338 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002339 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002340 if (resetDns) {
2341 flushVmDnsCache();
2342 if (VDBG) log("resetting DNS cache for " + iface);
2343 try {
2344 mNetd.flushInterfaceDnsCache(iface);
2345 } catch (Exception e) {
2346 // never crash - catch them all
2347 if (DBG) loge("Exception resetting dns cache: " + e);
2348 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002349 }
Robert Greenwalt4398f342013-05-23 18:33:06 -07002350 } else {
2351 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002352 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002353 }
2354 }
2355 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002356
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002357 // Update 464xlat state.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002358 NetworkStateTracker tracker = mNetTrackers[netType];
2359 if (mClat.requiresClat(netType, tracker)) {
Lorenzo Colitti4118d082013-03-28 14:13:43 +09002360 // If the connection was previously using clat, but is not using it now, stop the clat
2361 // daemon. Normally, this happens automatically when the connection disconnects, but if
2362 // the disconnect is not reported, or if the connection's LinkProperties changed for
2363 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2364 // still be running. If it's not running, then stopping it is a no-op.
2365 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2366 mClat.stopClat();
2367 }
2368 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002369 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2370 mClat.startClat(tracker);
2371 } else {
2372 mClat.stopClat();
2373 }
2374 }
2375
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002376 // TODO: Temporary notifying upstread change to Tethering.
2377 // @see bug/4455071
2378 /** Notify TetheringService if interface name has been changed. */
2379 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002380 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002381 if (isTetheringSupported()) {
2382 mTethering.handleTetherIfaceChange();
2383 }
2384 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002385 }
2386
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002387 /**
2388 * Add and remove routes using the old properties (null if not previously connected),
2389 * new properties (null if becoming disconnected). May even be double null, which
2390 * is a noop.
2391 * Uses isLinkDefault to determine if default routes should be set or conversely if
2392 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002393 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002394 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002395 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2396 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002397 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002398 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2399 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002400 if (curLp != null) {
2401 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002402 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002403 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002404 } else if (newLp != null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002405 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002406 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002407 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002408
Robert Greenwalt8d777252011-08-15 12:31:55 -07002409 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2410
Robert Greenwalt98107422011-07-22 11:55:33 -07002411 for (RouteInfo r : routeDiff.removed) {
2412 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002413 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2414 }
2415 if (isLinkDefault == false) {
2416 // remove from a secondary route table
2417 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002418 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002419 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002420
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002421 if (!isLinkDefault) {
2422 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002423 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002424 // routes changed - remove all old dns entries and add new
2425 if (curLp != null) {
2426 for (InetAddress oldDns : curLp.getDnses()) {
2427 removeRouteToAddress(curLp, oldDns);
2428 }
2429 }
2430 if (newLp != null) {
2431 for (InetAddress newDns : newLp.getDnses()) {
2432 addRouteToAddress(newLp, newDns);
2433 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002434 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002435 } else {
2436 // no change in routes, check for change in dns themselves
2437 for (InetAddress oldDns : dnsDiff.removed) {
2438 removeRouteToAddress(curLp, oldDns);
2439 }
2440 for (InetAddress newDns : dnsDiff.added) {
2441 addRouteToAddress(newLp, newDns);
2442 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002443 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002444 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002445
2446 for (RouteInfo r : routeDiff.added) {
2447 if (isLinkDefault || ! r.isDefaultRoute()) {
2448 addRoute(newLp, r, TO_DEFAULT_TABLE);
2449 } else {
2450 // add to a secondary route table
2451 addRoute(newLp, r, TO_SECONDARY_TABLE);
2452
2453 // many radios add a default route even when we don't want one.
2454 // remove the default route unless somebody else has asked for it
2455 String ifaceName = newLp.getInterfaceName();
2456 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2457 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2458 try {
2459 mNetd.removeRoute(ifaceName, r);
2460 } catch (Exception e) {
2461 // never crash - catch them all
2462 if (DBG) loge("Exception trying to remove a route: " + e);
2463 }
2464 }
2465 }
2466 }
2467
Robert Greenwalt8d777252011-08-15 12:31:55 -07002468 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002469 }
2470
2471
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002472 /**
2473 * Reads the network specific TCP buffer sizes from SystemProperties
2474 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2475 * wide use
2476 */
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002477 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002478 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002479 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002480
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002481 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002482 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002483
2484 // Setting to default values so we won't be stuck to previous values
2485 key = "net.tcp.buffersize.default";
2486 bufferSizes = SystemProperties.get(key);
2487 }
2488
2489 // Set values in kernel
2490 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002491 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002492 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002493 + "] which comes from [" + key + "]");
2494 }
2495 setBufferSize(bufferSizes);
2496 }
2497 }
2498
2499 /**
2500 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2501 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2502 *
2503 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2504 * writeMin, writeInitial, writeMax"
2505 */
2506 private void setBufferSize(String bufferSizes) {
2507 try {
2508 String[] values = bufferSizes.split(",");
2509
2510 if (values.length == 6) {
2511 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002512 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2513 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2514 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2515 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2516 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2517 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002518 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002519 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002520 }
2521 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002522 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002523 }
2524 }
2525
Robert Greenwalt2034b912009-08-12 16:08:25 -07002526 /**
2527 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2528 * on the highest priority active net which this process requested.
2529 * If there aren't any, clear it out
2530 */
Mattias Falkd697aa22011-08-23 14:15:13 +02002531 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002532 {
Mattias Falkd697aa22011-08-23 14:15:13 +02002533 if (VDBG) log("reassessPidDns for pid " + pid);
2534 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002535 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002536 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002537 continue;
2538 }
2539 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002540 if (nt.getNetworkInfo().isConnected() &&
2541 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002542 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002543 if (p == null) continue;
Mattias Falkd697aa22011-08-23 14:15:13 +02002544 if (mNetRequestersPids[i].contains(myPid)) {
2545 try {
2546 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2547 } catch (Exception e) {
2548 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002549 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002550 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002551 }
2552 }
2553 }
2554 // nothing found - delete
Mattias Falkd697aa22011-08-23 14:15:13 +02002555 try {
2556 mNetd.clearDnsInterfaceForPid(pid);
2557 } catch (Exception e) {
2558 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002559 }
2560 }
2561
Mattias Falkd697aa22011-08-23 14:15:13 +02002562 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002563 /*
2564 * Tell the VMs to toss their DNS caches
2565 */
2566 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2567 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002568 /*
2569 * Connectivity events can happen before boot has completed ...
2570 */
2571 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002572 final long ident = Binder.clearCallingIdentity();
2573 try {
2574 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2575 } finally {
2576 Binder.restoreCallingIdentity(ident);
2577 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002578 }
2579
Chia-chi Yehcc844502011-07-14 18:01:57 -07002580 // Caller must grab mDnsLock.
Mattias Falkd697aa22011-08-23 14:15:13 +02002581 private void updateDnsLocked(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002582 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002583 int last = 0;
2584 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002585 dnses = new ArrayList();
2586 dnses.add(mDefaultDns);
2587 if (DBG) {
2588 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002589 }
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002590 }
2591
Mattias Falkd697aa22011-08-23 14:15:13 +02002592 try {
2593 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Robert Greenwalte41e3b32013-02-11 15:25:10 -08002594 for (InetAddress dns : dnses) {
2595 ++last;
2596 String key = "net.dns" + last;
2597 String value = dns.getHostAddress();
2598 SystemProperties.set(key, value);
2599 }
2600 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2601 String key = "net.dns" + i;
2602 SystemProperties.set(key, "");
2603 }
2604 mNumDnsEntries = last;
Mattias Falkd697aa22011-08-23 14:15:13 +02002605 } catch (Exception e) {
2606 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002607 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002608 }
2609
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002610 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002611 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002612 NetworkStateTracker nt = mNetTrackers[netType];
2613 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002614 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002615 if (p == null) return;
2616 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002617 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002618 String network = nt.getNetworkInfo().getTypeName();
2619 synchronized (mDnsLock) {
2620 if (!mDnsOverridden) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002621 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalt94daa182010-09-01 11:34:05 -07002622 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002623 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002624 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002625 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002626 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltcd277852012-11-09 10:52:27 -08002627 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002628 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002629 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002630 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002631 // set per-pid dns for attached secondary nets
Mattias Falkd697aa22011-08-23 14:15:13 +02002632 List<Integer> pids = mNetRequestersPids[netType];
2633 for (Integer pid : pids) {
2634 try {
2635 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2636 } catch (Exception e) {
2637 Slog.e(TAG, "exception setting interface for pid: " + e);
2638 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002639 }
2640 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002641 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002642 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002643 }
2644
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002645 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002646 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2647 NETWORK_RESTORE_DELAY_PROP_NAME);
2648 if(restoreDefaultNetworkDelayStr != null &&
2649 restoreDefaultNetworkDelayStr.length() != 0) {
2650 try {
2651 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2652 } catch (NumberFormatException e) {
2653 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002654 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002655 // if the system property isn't set, use the value for the apn type
2656 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2657
2658 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2659 (mNetConfigs[networkType] != null)) {
2660 ret = mNetConfigs[networkType].restoreTime;
2661 }
2662 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002663 }
2664
2665 @Override
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002666 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2667 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002668 if (mContext.checkCallingOrSelfPermission(
2669 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002670 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002671 pw.println("Permission Denial: can't dump ConnectivityService " +
2672 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2673 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002674 return;
2675 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002676
2677 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002678 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002679 for (int i = 0; i < mNetTrackers.length; i++) {
2680 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002681 if (nst != null) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002682 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2683 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002684 if (nst.getNetworkInfo().isConnected()) {
2685 pw.println("Active network: " + nst.getNetworkInfo().
2686 getTypeName());
2687 }
2688 pw.println(nst.getNetworkInfo());
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002689 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002690 pw.println(nst);
2691 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002692 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002693 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002694 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002695
2696 pw.println("Network Requester Pids:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002697 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002698 for (int net : mPriorityList) {
2699 String pidString = net + ": ";
Mattias Falkd697aa22011-08-23 14:15:13 +02002700 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002701 pidString = pidString + pid.toString() + ", ";
2702 }
2703 pw.println(pidString);
2704 }
2705 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002706 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002707
2708 pw.println("FeatureUsers:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002709 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002710 for (Object requester : mFeatureUsers) {
2711 pw.println(requester.toString());
2712 }
2713 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002714 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002715
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002716 synchronized (this) {
2717 pw.println("NetworkTranstionWakeLock is currently " +
2718 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2719 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2720 }
2721 pw.println();
2722
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002723 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002724
2725 if (mInetLog != null) {
2726 pw.println();
2727 pw.println("Inet condition reports:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002728 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002729 for(int i = 0; i < mInetLog.size(); i++) {
2730 pw.println(mInetLog.get(i));
2731 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002732 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002733 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002734 }
2735
Robert Greenwalt2034b912009-08-12 16:08:25 -07002736 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002737 private class NetworkStateTrackerHandler extends Handler {
2738 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002739 super(looper);
2740 }
2741
The Android Open Source Project28527d22009-03-03 19:31:44 -08002742 @Override
2743 public void handleMessage(Message msg) {
2744 NetworkInfo info;
2745 switch (msg.what) {
2746 case NetworkStateTracker.EVENT_STATE_CHANGED:
2747 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002748 int type = info.getType();
2749 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002750
Wink Savillea7d56572011-09-21 11:05:43 -07002751 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2752 (state == NetworkInfo.State.DISCONNECTED)) {
2753 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002754 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002755 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002756 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002757
Jeff Sharkey876ddc92012-11-09 15:57:02 -08002758 EventLogTags.writeConnectivityStateChanged(
2759 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002760
2761 if (info.getDetailedState() ==
2762 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002763 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002764 } else if (info.getDetailedState() ==
2765 DetailedState.CAPTIVE_PORTAL_CHECK) {
2766 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002767 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002768 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002769 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002770 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002771 // the logic here is, handle SUSPENDED the same as
2772 // DISCONNECTED. The only difference being we are
2773 // broadcasting an intent with NetworkInfo that's
2774 // suspended. This allows the applications an
2775 // opportunity to handle DISCONNECTED and SUSPENDED
2776 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002777 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002778 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002779 handleConnect(info);
2780 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002781 if (mLockdownTracker != null) {
2782 mLockdownTracker.onNetworkInfoChanged(info);
2783 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002784 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002785 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002786 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002787 // TODO: Temporary allowing network configuration
2788 // change not resetting sockets.
2789 // @see bug/4455071
2790 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002791 break;
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07002792 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2793 info = (NetworkInfo) msg.obj;
2794 type = info.getType();
2795 updateNetworkSettings(mNetTrackers[type]);
2796 break;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002797 }
2798 }
2799 }
2800
2801 private class InternalHandler extends Handler {
2802 public InternalHandler(Looper looper) {
2803 super(looper);
2804 }
2805
2806 @Override
2807 public void handleMessage(Message msg) {
2808 NetworkInfo info;
2809 switch (msg.what) {
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002810 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002811 String causedBy = null;
2812 synchronized (ConnectivityService.this) {
2813 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2814 mNetTransitionWakeLock.isHeld()) {
2815 mNetTransitionWakeLock.release();
2816 causedBy = mNetTransitionWakeLockCausedBy;
2817 }
2818 }
2819 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002820 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002821 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002822 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002823 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002824 FeatureUser u = (FeatureUser)msg.obj;
2825 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002826 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002827 case EVENT_INET_CONDITION_CHANGE:
2828 {
2829 int netType = msg.arg1;
2830 int condition = msg.arg2;
2831 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002832 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002833 }
2834 case EVENT_INET_CONDITION_HOLD_END:
2835 {
2836 int netType = msg.arg1;
2837 int sequence = msg.arg2;
Wink Saville151eaa62013-01-31 00:30:13 +00002838 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002839 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002840 }
2841 case EVENT_SET_NETWORK_PREFERENCE:
2842 {
2843 int preference = msg.arg1;
2844 handleSetNetworkPreference(preference);
2845 break;
2846 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002847 case EVENT_SET_MOBILE_DATA:
2848 {
2849 boolean enabled = (msg.arg1 == ENABLED);
2850 handleSetMobileData(enabled);
2851 break;
2852 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002853 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2854 {
2855 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002856 break;
2857 }
2858 case EVENT_SET_DEPENDENCY_MET:
2859 {
2860 boolean met = (msg.arg1 == ENABLED);
2861 handleSetDependencyMet(msg.arg2, met);
2862 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002863 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002864 case EVENT_RESTORE_DNS:
2865 {
2866 if (mActiveDefaultNetwork != -1) {
2867 handleDnsConfigurationChange(mActiveDefaultNetwork);
2868 }
2869 break;
2870 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002871 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2872 {
2873 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002874 sendStickyBroadcast(intent);
2875 break;
2876 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002877 case EVENT_SET_POLICY_DATA_ENABLE: {
2878 final int networkType = msg.arg1;
2879 final boolean enabled = msg.arg2 == ENABLED;
2880 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002881 break;
2882 }
2883 case EVENT_VPN_STATE_CHANGED: {
2884 if (mLockdownTracker != null) {
2885 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2886 }
2887 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07002888 }
Wink Saville32506bc2013-06-29 21:10:57 -07002889 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2890 int tag = mEnableFailFastMobileDataTag.get();
2891 if (msg.arg1 == tag) {
2892 MobileDataStateTracker mobileDst =
2893 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2894 if (mobileDst != null) {
2895 mobileDst.setEnableFailFastMobileData(msg.arg2);
2896 }
2897 } else {
2898 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2899 + " != tag:" + tag);
2900 }
2901 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002902 }
2903 }
2904 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002905
2906 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002907 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002908 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002909
2910 if (isTetheringSupported()) {
2911 return mTethering.tether(iface);
2912 } else {
2913 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2914 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002915 }
2916
2917 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002918 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002919 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002920
2921 if (isTetheringSupported()) {
2922 return mTethering.untether(iface);
2923 } else {
2924 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2925 }
2926 }
2927
2928 // javadoc from interface
2929 public int getLastTetherError(String iface) {
2930 enforceTetherAccessPermission();
2931
2932 if (isTetheringSupported()) {
2933 return mTethering.getLastTetherError(iface);
2934 } else {
2935 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2936 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002937 }
2938
2939 // TODO - proper iface API for selection by property, inspection, etc
2940 public String[] getTetherableUsbRegexs() {
2941 enforceTetherAccessPermission();
2942 if (isTetheringSupported()) {
2943 return mTethering.getTetherableUsbRegexs();
2944 } else {
2945 return new String[0];
2946 }
2947 }
2948
2949 public String[] getTetherableWifiRegexs() {
2950 enforceTetherAccessPermission();
2951 if (isTetheringSupported()) {
2952 return mTethering.getTetherableWifiRegexs();
2953 } else {
2954 return new String[0];
2955 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002956 }
2957
Danica Chang96567052010-08-11 14:54:43 -07002958 public String[] getTetherableBluetoothRegexs() {
2959 enforceTetherAccessPermission();
2960 if (isTetheringSupported()) {
2961 return mTethering.getTetherableBluetoothRegexs();
2962 } else {
2963 return new String[0];
2964 }
2965 }
2966
Mike Lockwooded4a1742011-07-19 13:04:47 -07002967 public int setUsbTethering(boolean enable) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002968 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07002969 if (isTetheringSupported()) {
2970 return mTethering.setUsbTethering(enable);
2971 } else {
2972 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2973 }
2974 }
2975
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002976 // TODO - move iface listing, queries, etc to new module
2977 // javadoc from interface
2978 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002979 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002980 return mTethering.getTetherableIfaces();
2981 }
2982
2983 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002984 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002985 return mTethering.getTetheredIfaces();
2986 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002987
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002988 @Override
2989 public String[] getTetheredIfacePairs() {
2990 enforceTetherAccessPermission();
2991 return mTethering.getTetheredIfacePairs();
2992 }
2993
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002994 public String[] getTetheringErroredIfaces() {
2995 enforceTetherAccessPermission();
2996 return mTethering.getErroredIfaces();
2997 }
2998
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002999 // if ro.tether.denied = true we default to no tethering
3000 // gservices could set the secure setting to 1 though to enable it on a build where it
3001 // had previously been turned off.
3002 public boolean isTetheringSupported() {
3003 enforceTetherAccessPermission();
3004 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownc67cf562012-09-25 15:03:20 -07003005 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3006 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08003007 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003008 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003009
3010 // An API NetworkStateTrackers can call when they lose their network.
3011 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3012 // whichever happens first. The timer is started by the first caller and not
3013 // restarted by subsequent callers.
3014 public void requestNetworkTransitionWakelock(String forWhom) {
3015 enforceConnectivityInternalPermission();
3016 synchronized (this) {
3017 if (mNetTransitionWakeLock.isHeld()) return;
3018 mNetTransitionWakeLockSerialNumber++;
3019 mNetTransitionWakeLock.acquire();
3020 mNetTransitionWakeLockCausedBy = forWhom;
3021 }
3022 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003023 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003024 mNetTransitionWakeLockSerialNumber, 0),
3025 mNetTransitionWakeLockTimeout);
3026 return;
3027 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003028
Robert Greenwalt986c7412010-09-08 15:24:47 -07003029 // 100 percent is full good, 0 is full bad.
3030 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003031 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003032 mContext.enforceCallingOrSelfPermission(
3033 android.Manifest.permission.STATUS_BAR,
3034 "ConnectivityService");
3035
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003036 if (DBG) {
3037 int pid = getCallingPid();
3038 int uid = getCallingUid();
3039 String s = pid + "(" + uid + ") reports inet is " +
3040 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3041 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3042 mInetLog.add(s);
3043 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3044 mInetLog.remove(0);
3045 }
3046 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003047 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003048 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3049 }
3050
3051 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003052 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003053 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003054 return;
3055 }
3056 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003057 if (DBG) log("handleInetConditionChange: net=" + netType +
3058 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003059 return;
3060 }
Wink Savillea7d56572011-09-21 11:05:43 -07003061 if (VDBG) {
3062 log("handleInetConditionChange: net=" +
3063 netType + ", condition=" + condition +
Wink Saville151eaa62013-01-31 00:30:13 +00003064 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003065 }
Wink Saville151eaa62013-01-31 00:30:13 +00003066 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003067 int delay;
3068 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003069 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003070 // setup a new hold to debounce this
Wink Saville151eaa62013-01-31 00:30:13 +00003071 if (mDefaultInetCondition > 50) {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003072 delay = Settings.Global.getInt(mContext.getContentResolver(),
3073 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003074 } else {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003075 delay = Settings.Global.getInt(mContext.getContentResolver(),
3076 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003077 }
3078 mInetConditionChangeInFlight = true;
3079 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville151eaa62013-01-31 00:30:13 +00003080 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003081 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003082 // we've set the new condition, when this hold ends that will get picked up
3083 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003084 }
3085 }
3086
Wink Saville151eaa62013-01-31 00:30:13 +00003087 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003088 if (DBG) {
Wink Saville151eaa62013-01-31 00:30:13 +00003089 log("handleInetConditionHoldEnd: net=" + netType +
3090 ", condition=" + mDefaultInetCondition +
3091 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003092 }
3093 mInetConditionChangeInFlight = false;
3094
3095 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003096 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003097 return;
3098 }
3099 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003100 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003101 return;
3102 }
Wink Saville151eaa62013-01-31 00:30:13 +00003103 // TODO: Figure out why this optimization sometimes causes a
3104 // change in mDefaultInetCondition to be missed and the
3105 // UI to not be updated.
3106 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3107 // if (DBG) log("no change in condition - aborting");
3108 // return;
3109 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003110 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3111 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003112 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003113 return;
3114 }
Wink Saville151eaa62013-01-31 00:30:13 +00003115 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003116 sendInetConditionBroadcast(networkInfo);
3117 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003118 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003119
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003120 public ProxyProperties getProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003121 // this information is already available as a world read/writable jvm property
3122 // so this API change wouldn't have a benifit. It also breaks the passing
3123 // of proxy info to all the JVMs.
3124 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003125 synchronized (mProxyLock) {
3126 if (mGlobalProxy != null) return mGlobalProxy;
3127 return (mDefaultProxyDisabled ? null : mDefaultProxy);
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003128 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003129 }
3130
3131 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003132 enforceConnectivityInternalPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003133 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003134 if (proxyProperties == mGlobalProxy) return;
3135 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3136 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3137
3138 String host = "";
3139 int port = 0;
3140 String exclList = "";
3141 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3142 mGlobalProxy = new ProxyProperties(proxyProperties);
3143 host = mGlobalProxy.getHost();
3144 port = mGlobalProxy.getPort();
3145 exclList = mGlobalProxy.getExclusionList();
3146 } else {
3147 mGlobalProxy = null;
3148 }
3149 ContentResolver res = mContext.getContentResolver();
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003150 final long token = Binder.clearCallingIdentity();
3151 try {
3152 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3153 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3154 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3155 exclList);
3156 } finally {
3157 Binder.restoreCallingIdentity(token);
3158 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003159 }
3160
3161 if (mGlobalProxy == null) {
3162 proxyProperties = mDefaultProxy;
3163 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003164 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003165 }
3166
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003167 private void loadGlobalProxy() {
3168 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003169 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3170 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3171 String exclList = Settings.Global.getString(res,
3172 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003173 if (!TextUtils.isEmpty(host)) {
3174 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003175 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003176 mGlobalProxy = proxyProperties;
3177 }
3178 }
3179 }
3180
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003181 public ProxyProperties getGlobalProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003182 // this information is already available as a world read/writable jvm property
3183 // so this API change wouldn't have a benifit. It also breaks the passing
3184 // of proxy info to all the JVMs.
3185 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003186 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003187 return mGlobalProxy;
3188 }
3189 }
3190
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003191 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3192 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3193 proxy = null;
3194 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003195 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003196 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003197 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003198 mDefaultProxy = proxy;
3199
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003200 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003201 if (!mDefaultProxyDisabled) {
3202 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003203 }
3204 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003205 }
3206
3207 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003208 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3209 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003210 if (!TextUtils.isEmpty(proxy)) {
3211 String data[] = proxy.split(":");
Andreas Huber23bff232013-05-28 15:17:37 -07003212 if (data.length == 0) {
3213 return;
3214 }
3215
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003216 String proxyHost = data[0];
3217 int proxyPort = 8080;
3218 if (data.length > 1) {
3219 try {
3220 proxyPort = Integer.parseInt(data[1]);
3221 } catch (NumberFormatException e) {
3222 return;
3223 }
3224 }
3225 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3226 setGlobalProxy(p);
Andreas Huber23bff232013-05-28 15:17:37 -07003227 } else {
3228 setGlobalProxy(null);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003229 }
3230 }
3231
3232 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003233 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07003234 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003235 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003236 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3237 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003238 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003239 final long ident = Binder.clearCallingIdentity();
3240 try {
3241 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3242 } finally {
3243 Binder.restoreCallingIdentity(ident);
3244 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003245 }
3246
3247 private static class SettingsObserver extends ContentObserver {
3248 private int mWhat;
3249 private Handler mHandler;
3250 SettingsObserver(Handler handler, int what) {
3251 super(handler);
3252 mHandler = handler;
3253 mWhat = what;
3254 }
3255
3256 void observe(Context context) {
3257 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003258 resolver.registerContentObserver(Settings.Global.getUriFor(
3259 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003260 }
3261
3262 @Override
3263 public void onChange(boolean selfChange) {
3264 mHandler.obtainMessage(mWhat).sendToTarget();
3265 }
3266 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003267
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003268 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003269 Slog.d(TAG, s);
3270 }
3271
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003272 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003273 Slog.e(TAG, s);
3274 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003275
repo syncf5de5572011-07-29 23:55:49 -07003276 int convertFeatureToNetworkType(int networkType, String feature) {
3277 int usedNetworkType = networkType;
3278
3279 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3280 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3281 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3282 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3283 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3284 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3285 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3286 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3287 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3288 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3289 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3290 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3291 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3292 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3293 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3294 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3295 } else {
3296 Slog.e(TAG, "Can't match any mobile netTracker!");
3297 }
3298 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3299 if (TextUtils.equals(feature, "p2p")) {
3300 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3301 } else {
3302 Slog.e(TAG, "Can't match any wifi netTracker!");
3303 }
3304 } else {
3305 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003306 }
repo syncf5de5572011-07-29 23:55:49 -07003307 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003308 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003309
3310 private static <T> T checkNotNull(T value, String message) {
3311 if (value == null) {
3312 throw new NullPointerException(message);
3313 }
3314 return value;
3315 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003316
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003317 /**
3318 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003319 * VpnBuilder and not available in ConnectivityManager. Permissions
3320 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003321 * @hide
3322 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003323 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003324 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003325 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003326 try {
3327 int type = mActiveDefaultNetwork;
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003328 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt15a41532012-08-21 19:27:00 -07003329 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003330 synchronized(mVpns) {
3331 mVpns.get(user).protect(socket,
3332 mNetTrackers[type].getLinkProperties().getInterfaceName());
3333 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003334 return true;
3335 }
3336 } catch (Exception e) {
3337 // ignore
3338 } finally {
3339 try {
3340 socket.close();
3341 } catch (Exception e) {
3342 // ignore
3343 }
3344 }
3345 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003346 }
3347
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003348 /**
3349 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003350 * and not available in ConnectivityManager. Permissions are checked
3351 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003352 * @hide
3353 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003354 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003355 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003356 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003357 int user = UserHandle.getUserId(Binder.getCallingUid());
3358 synchronized(mVpns) {
3359 return mVpns.get(user).prepare(oldPackage, newPackage);
3360 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003361 }
3362
Chad Brubaker11f22252013-07-11 13:29:30 -07003363 @Override
3364 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3365 enforceMarkNetworkSocketPermission();
3366 final long token = Binder.clearCallingIdentity();
3367 try {
3368 int mark = mNetd.getMarkForUid(uid);
3369 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3370 if (mark == -1) {
3371 mark = 0;
3372 }
3373 NetworkUtils.markSocket(socket.getFd(), mark);
3374 } catch (RemoteException e) {
3375 } finally {
3376 Binder.restoreCallingIdentity(token);
3377 }
3378 }
3379
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003380 /**
3381 * Configure a TUN interface and return its file descriptor. Parameters
3382 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003383 * and not available in ConnectivityManager. Permissions are checked in
3384 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003385 * @hide
3386 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003387 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003388 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003389 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003390 int user = UserHandle.getUserId(Binder.getCallingUid());
3391 synchronized(mVpns) {
3392 return mVpns.get(user).establish(config);
3393 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003394 }
3395
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003396 /**
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003397 * Start legacy VPN, controlling native daemons as needed. Creates a
3398 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003399 */
3400 @Override
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003401 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003402 throwIfLockdownEnabled();
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003403 final LinkProperties egress = getActiveLinkProperties();
3404 if (egress == null) {
3405 throw new IllegalStateException("Missing active network connection");
3406 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003407 int user = UserHandle.getUserId(Binder.getCallingUid());
3408 synchronized(mVpns) {
3409 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3410 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003411 }
3412
3413 /**
3414 * Return the information of the ongoing legacy VPN. This method is used
3415 * by VpnSettings and not available in ConnectivityManager. Permissions
3416 * are checked in Vpn class.
3417 * @hide
3418 */
3419 @Override
3420 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003421 throwIfLockdownEnabled();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003422 int user = UserHandle.getUserId(Binder.getCallingUid());
3423 synchronized(mVpns) {
3424 return mVpns.get(user).getLegacyVpnInfo();
3425 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003426 }
3427
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003428 /**
Chad Brubaker94f3c8c2013-07-16 18:59:12 -07003429 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3430 * not available in ConnectivityManager.
3431 * Permissions are checked in Vpn class.
3432 * @hide
3433 */
3434 @Override
3435 public VpnConfig getVpnConfig() {
3436 int user = UserHandle.getUserId(Binder.getCallingUid());
3437 synchronized(mVpns) {
3438 return mVpns.get(user).getVpnConfig();
3439 }
3440 }
3441
3442 /**
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003443 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3444 * through NetworkStateTracker since it works differently. For example, it
3445 * needs to override DNS servers but never takes the default routes. It
3446 * relies on another data network, and it could keep existing connections
3447 * alive after reconnecting, switching between networks, or even resuming
3448 * from deep sleep. Calls from applications should be done synchronously
3449 * to avoid race conditions. As these are all hidden APIs, refactoring can
3450 * be done whenever a better abstraction is developed.
3451 */
3452 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003453 private VpnCallback() {
3454 }
3455
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003456 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003457 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003458 }
3459
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003460 public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07003461 if (dnsServers == null) {
3462 restore();
3463 return;
3464 }
3465
3466 // Convert DNS servers into addresses.
3467 List<InetAddress> addresses = new ArrayList<InetAddress>();
3468 for (String address : dnsServers) {
3469 // Double check the addresses and remove invalid ones.
3470 try {
3471 addresses.add(InetAddress.parseNumericAddress(address));
3472 } catch (Exception e) {
3473 // ignore
3474 }
3475 }
3476 if (addresses.isEmpty()) {
3477 restore();
3478 return;
3479 }
3480
3481 // Concatenate search domains into a string.
3482 StringBuilder buffer = new StringBuilder();
3483 if (searchDomains != null) {
3484 for (String domain : searchDomains) {
3485 buffer.append(domain).append(' ');
3486 }
3487 }
3488 String domains = buffer.toString().trim();
3489
3490 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003491 synchronized (mDnsLock) {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003492 updateDnsLocked("VPN", iface, addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003493 mDnsOverridden = true;
3494 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003495
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003496 // Temporarily disable the default proxy (not global).
3497 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003498 mDefaultProxyDisabled = true;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003499 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003500 sendProxyBroadcast(null);
3501 }
3502 }
3503
3504 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003505 }
3506
Chia-chi Yehcc844502011-07-14 18:01:57 -07003507 public void restore() {
3508 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003509 if (mDnsOverridden) {
3510 mDnsOverridden = false;
3511 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003512 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003513 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003514 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003515 mDefaultProxyDisabled = false;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003516 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003517 sendProxyBroadcast(mDefaultProxy);
3518 }
3519 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003520 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003521
3522 public void protect(ParcelFileDescriptor socket) {
3523 try {
3524 final int mark = mNetd.getMarkForProtect();
3525 NetworkUtils.markSocket(socket.getFd(), mark);
3526 } catch (RemoteException e) {
3527 }
3528 }
3529
3530 public void setRoutes(String interfaze, List<RouteInfo> routes) {
3531 for (RouteInfo route : routes) {
3532 try {
3533 mNetd.setMarkedForwardingRoute(interfaze, route);
3534 } catch (RemoteException e) {
3535 }
3536 }
3537 }
3538
3539 public void setMarkedForwarding(String interfaze) {
3540 try {
3541 mNetd.setMarkedForwarding(interfaze);
3542 } catch (RemoteException e) {
3543 }
3544 }
3545
3546 public void clearMarkedForwarding(String interfaze) {
3547 try {
3548 mNetd.clearMarkedForwarding(interfaze);
3549 } catch (RemoteException e) {
3550 }
3551 }
3552
3553 public void addUserForwarding(String interfaze, int uid) {
3554 int uidStart = uid * UserHandle.PER_USER_RANGE;
3555 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3556 addUidForwarding(interfaze, uidStart, uidEnd);
3557 }
3558
3559 public void clearUserForwarding(String interfaze, int uid) {
3560 int uidStart = uid * UserHandle.PER_USER_RANGE;
3561 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
3562 clearUidForwarding(interfaze, uidStart, uidEnd);
3563 }
3564
3565 public void addUidForwarding(String interfaze, int uidStart, int uidEnd) {
3566 try {
3567 mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
3568 mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
3569 } catch (RemoteException e) {
3570 }
3571
3572 }
3573
3574 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd) {
3575 try {
3576 mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
3577 mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
3578 } catch (RemoteException e) {
3579 }
3580
3581 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003582 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003583
3584 @Override
3585 public boolean updateLockdownVpn() {
Jeff Sharkey760c6202013-01-31 17:22:26 -08003586 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3587 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3588 return false;
3589 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003590
3591 // Tear down existing lockdown if profile was removed
3592 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3593 if (mLockdownEnabled) {
Kenny Root0ded63c2013-02-14 10:18:38 -08003594 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003595 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3596 return false;
3597 }
3598
3599 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3600 final VpnProfile profile = VpnProfile.decode(
3601 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubakerb7652cd2013-06-14 11:16:51 -07003602 int user = UserHandle.getUserId(Binder.getCallingUid());
3603 synchronized(mVpns) {
3604 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3605 profile));
3606 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003607 } else {
3608 setLockdownTracker(null);
3609 }
3610
3611 return true;
3612 }
3613
3614 /**
3615 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3616 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3617 */
3618 private void setLockdownTracker(LockdownVpnTracker tracker) {
3619 // Shutdown any existing tracker
3620 final LockdownVpnTracker existing = mLockdownTracker;
3621 mLockdownTracker = null;
3622 if (existing != null) {
3623 existing.shutdown();
3624 }
3625
3626 try {
3627 if (tracker != null) {
3628 mNetd.setFirewallEnabled(true);
Jeff Sharkeydb44d2c2013-02-28 16:57:58 -08003629 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003630 mLockdownTracker = tracker;
3631 mLockdownTracker.init();
3632 } else {
3633 mNetd.setFirewallEnabled(false);
3634 }
3635 } catch (RemoteException e) {
3636 // ignored; NMS lives inside system_server
3637 }
3638 }
3639
3640 private void throwIfLockdownEnabled() {
3641 if (mLockdownEnabled) {
3642 throw new IllegalStateException("Unavailable in lockdown mode");
3643 }
3644 }
Robert Greenwalt15a41532012-08-21 19:27:00 -07003645
3646 public void supplyMessenger(int networkType, Messenger messenger) {
3647 enforceConnectivityInternalPermission();
3648
3649 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3650 mNetTrackers[networkType].supplyMessenger(messenger);
3651 }
3652 }
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -07003653
3654 public int findConnectionTypeForIface(String iface) {
3655 enforceConnectivityInternalPermission();
3656
3657 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3658 for (NetworkStateTracker tracker : mNetTrackers) {
3659 if (tracker != null) {
3660 LinkProperties lp = tracker.getLinkProperties();
3661 if (lp != null && iface.equals(lp.getInterfaceName())) {
3662 return tracker.getNetworkInfo().getType();
3663 }
3664 }
3665 }
3666 return ConnectivityManager.TYPE_NONE;
3667 }
Wink Saville32506bc2013-06-29 21:10:57 -07003668
3669 /**
3670 * Have mobile data fail fast if enabled.
3671 *
3672 * @param enabled DctConstants.ENABLED/DISABLED
3673 */
3674 private void setEnableFailFastMobileData(int enabled) {
3675 int tag;
3676
3677 if (enabled == DctConstants.ENABLED) {
3678 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3679 } else {
3680 tag = mEnableFailFastMobileDataTag.get();
3681 }
3682 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3683 enabled));
3684 }
3685
3686 @Override
3687 public int checkMobileProvisioning(boolean sendNotification, int suggestedTimeOutMs,
3688 final ResultReceiver resultReceiver) {
3689 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3690 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3691 + " resultReceiver=" + resultReceiver);
3692 enforceChangePermission();
3693
3694 int timeOutMs = suggestedTimeOutMs;
3695 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3696 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3697 }
3698
Wink Savilled469c472013-07-02 10:55:14 -07003699 // Check that mobile networks are supported
3700 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3701 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3702 log("checkMobileProvisioning: X no mobile network");
3703 if (resultReceiver != null) {
3704 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3705 }
3706 return timeOutMs;
3707 }
3708
Wink Saville32506bc2013-06-29 21:10:57 -07003709 final long token = Binder.clearCallingIdentity();
3710 try {
3711 CheckMp checkMp = new CheckMp(mContext, this);
3712 CheckMp.CallBack cb = new CheckMp.CallBack() {
3713 @Override
3714 void onComplete(Integer result) {
3715 log("CheckMp.onComplete: result=" + result);
3716 if (resultReceiver != null) {
3717 log("CheckMp.onComplete: send result");
3718 resultReceiver.send(result, null);
3719 }
3720 NetworkInfo ni =
3721 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3722 switch(result) {
3723 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3724 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3725 log("CheckMp.onComplete: ignore, connected or no connection");
3726 break;
3727 }
3728 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3729 log("CheckMp.onComplete: warm sim");
3730 String url = getProvisioningUrl();
3731 if (TextUtils.isEmpty(url)) {
3732 url = mContext.getResources()
3733 .getString(R.string.mobile_redirected_provisioning_url);
3734 }
3735 if (TextUtils.isEmpty(url) == false) {
3736 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3737 setNotificationVisible(true, ni, url);
3738 } else {
3739 log("CheckMp.onComplete: warm sim (redirected), no url");
3740 }
3741 break;
3742 }
3743 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3744 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
3745 String url = getProvisioningUrl();
3746 if (TextUtils.isEmpty(url) == false) {
3747 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3748 setNotificationVisible(true, ni, url);
3749 } else {
3750 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3751 }
3752 break;
3753 }
3754 default: {
3755 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3756 break;
3757 }
3758 }
3759 }
3760 };
3761 CheckMp.Params params =
3762 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3763 log("checkMobileProvisioning: params=" + params);
3764 setNotificationVisible(false, null, null);
3765 checkMp.execute(params);
3766 } finally {
3767 Binder.restoreCallingIdentity(token);
3768 log("checkMobileProvisioning: X");
3769 }
3770 return timeOutMs;
3771 }
3772
3773 static class CheckMp extends
3774 AsyncTask<CheckMp.Params, Void, Integer> {
3775 private static final String CHECKMP_TAG = "CheckMp";
3776 public static final int MAX_TIMEOUT_MS = 60000;
3777 private static final int SOCKET_TIMEOUT_MS = 5000;
3778 private Context mContext;
3779 private ConnectivityService mCs;
3780 private TelephonyManager mTm;
3781 private Params mParams;
3782
3783 /**
3784 * Parameters for AsyncTask.execute
3785 */
3786 static class Params {
3787 private String mUrl;
3788 private long mTimeOutMs;
3789 private CallBack mCb;
3790
3791 Params(String url, long timeOutMs, CallBack cb) {
3792 mUrl = url;
3793 mTimeOutMs = timeOutMs;
3794 mCb = cb;
3795 }
3796
3797 @Override
3798 public String toString() {
3799 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3800 }
3801 }
3802
3803 /**
3804 * The call back object passed in Params. onComplete will be called
3805 * on the main thread.
3806 */
3807 abstract static class CallBack {
3808 // Called on the main thread.
3809 abstract void onComplete(Integer result);
3810 }
3811
3812 public CheckMp(Context context, ConnectivityService cs) {
3813 mContext = context;
3814 mCs = cs;
3815
3816 // Setup access to TelephonyService we'll be using.
3817 mTm = (TelephonyManager) mContext.getSystemService(
3818 Context.TELEPHONY_SERVICE);
3819 }
3820
3821 /**
3822 * Get the default url to use for the test.
3823 */
3824 public String getDefaultUrl() {
3825 // See http://go/clientsdns for usage approval
3826 String server = Settings.Global.getString(mContext.getContentResolver(),
3827 Settings.Global.CAPTIVE_PORTAL_SERVER);
3828 if (server == null) {
3829 server = "clients3.google.com";
3830 }
3831 return "http://" + server + "/generate_204";
3832 }
3833
3834 /**
3835 * Detect if its possible to connect to the http url. DNS based detection techniques
3836 * do not work at all hotspots. The best way to check is to perform a request to
3837 * a known address that fetches the data we expect.
3838 */
3839 private synchronized Integer isMobileOk(Params params) {
3840 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3841 Uri orgUri = Uri.parse(params.mUrl);
3842 Random rand = new Random();
3843 mParams = params;
3844
3845 try {
3846 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3847 log("isMobileOk: not mobile capable");
3848 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3849 return result;
3850 }
3851
3852 // Enable fail fast as we'll do retries here and use a
3853 // hipri connection so the default connection stays active.
3854 log("isMobileOk: start hipri url=" + params.mUrl);
3855 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3856 mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3857 Phone.FEATURE_ENABLE_HIPRI, new Binder());
3858
3859 // Continue trying to connect until time has run out
3860 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3861 while(SystemClock.elapsedRealtime() < endTime) {
3862 try {
3863 // Wait for hipri to connect.
3864 // TODO: Don't poll and handle situation where hipri fails
3865 // because default is retrying. See b/9569540
3866 NetworkInfo.State state = mCs
3867 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3868 if (state != NetworkInfo.State.CONNECTED) {
3869 log("isMobileOk: not connected ni=" +
3870 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3871 sleep(1);
3872 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3873 continue;
3874 }
3875
3876 // Get of the addresses associated with the url host. We need to use the
3877 // address otherwise HttpURLConnection object will use the name to get
3878 // the addresses and is will try every address but that will bypass the
3879 // route to host we setup and the connection could succeed as the default
3880 // interface might be connected to the internet via wifi or other interface.
3881 InetAddress[] addresses;
3882 try {
3883 addresses = InetAddress.getAllByName(orgUri.getHost());
3884 } catch (UnknownHostException e) {
3885 log("isMobileOk: UnknownHostException");
3886 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3887 return result;
3888 }
3889 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3890
3891 // Get the type of addresses supported by this link
3892 LinkProperties lp = mCs.getLinkProperties(
3893 ConnectivityManager.TYPE_MOBILE_HIPRI);
3894 boolean linkHasIpv4 = hasIPv4Address(lp);
3895 boolean linkHasIpv6 = hasIPv6Address(lp);
3896 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3897 + " linkHasIpv6=" + linkHasIpv6);
3898
3899 // Loop through at most 3 valid addresses or all of the address or until
3900 // we run out of time
3901 int loops = Math.min(3, addresses.length);
3902 for(int validAddr=0, addrTried=0;
3903 (validAddr < loops) && (addrTried < addresses.length)
3904 && (SystemClock.elapsedRealtime() < endTime);
3905 addrTried ++) {
3906
3907 // Choose the address at random but make sure its type is supported
3908 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3909 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3910 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3911 // Valid address, so use it
3912 validAddr += 1;
3913 } else {
3914 // Invalid address so try next address
3915 continue;
3916 }
3917
3918 // Make a route to host so we check the specific interface.
3919 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3920 hostAddr.getAddress())) {
3921 // Wait a short time to be sure the route is established ??
3922 log("isMobileOk:"
3923 + " wait to establish route to hostAddr=" + hostAddr);
3924 sleep(3);
3925 } else {
3926 log("isMobileOk:"
3927 + " could not establish route to hostAddr=" + hostAddr);
3928 continue;
3929 }
3930
3931 // Rewrite the url to have numeric address to use the specific route.
3932 // I also set the "Connection" to "Close" as by default "Keep-Alive"
3933 // is used which is useless in this case.
3934 URL newUrl = new URL(orgUri.getScheme() + "://"
3935 + hostAddr.getHostAddress() + orgUri.getPath());
3936 log("isMobileOk: newUrl=" + newUrl);
3937
3938 HttpURLConnection urlConn = null;
3939 try {
3940 // Open the connection set the request header and get the response
3941 urlConn = (HttpURLConnection) newUrl.openConnection(
3942 java.net.Proxy.NO_PROXY);
3943 urlConn.setInstanceFollowRedirects(false);
3944 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3945 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3946 urlConn.setUseCaches(false);
3947 urlConn.setAllowUserInteraction(false);
3948 urlConn.setRequestProperty("Connection", "close");
3949 int responseCode = urlConn.getResponseCode();
3950 if (responseCode == 204) {
3951 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
3952 } else {
3953 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3954 }
3955 log("isMobileOk: connected responseCode=" + responseCode);
3956 urlConn.disconnect();
3957 urlConn = null;
3958 return result;
3959 } catch (Exception e) {
3960 log("isMobileOk: HttpURLConnection Exception e=" + e);
3961 if (urlConn != null) {
3962 urlConn.disconnect();
3963 urlConn = null;
3964 }
3965 }
3966 }
3967 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3968 log("isMobileOk: loops|timed out");
3969 return result;
3970 } catch (Exception e) {
3971 log("isMobileOk: Exception e=" + e);
3972 continue;
3973 }
3974 }
3975 log("isMobileOk: timed out");
3976 } finally {
3977 log("isMobileOk: F stop hipri");
3978 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3979 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3980 Phone.FEATURE_ENABLE_HIPRI);
3981 log("isMobileOk: X result=" + result);
3982 }
3983 return result;
3984 }
3985
3986 @Override
3987 protected Integer doInBackground(Params... params) {
3988 return isMobileOk(params[0]);
3989 }
3990
3991 @Override
3992 protected void onPostExecute(Integer result) {
3993 log("onPostExecute: result=" + result);
3994 if ((mParams != null) && (mParams.mCb != null)) {
3995 mParams.mCb.onComplete(result);
3996 }
3997 }
3998
3999 private String inetAddressesToString(InetAddress[] addresses) {
4000 StringBuffer sb = new StringBuffer();
4001 boolean firstTime = true;
4002 for(InetAddress addr : addresses) {
4003 if (firstTime) {
4004 firstTime = false;
4005 } else {
4006 sb.append(",");
4007 }
4008 sb.append(addr);
4009 }
4010 return sb.toString();
4011 }
4012
4013 private void printNetworkInfo() {
4014 boolean hasIccCard = mTm.hasIccCard();
4015 int simState = mTm.getSimState();
4016 log("hasIccCard=" + hasIccCard
4017 + " simState=" + simState);
4018 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4019 if (ni != null) {
4020 log("ni.length=" + ni.length);
4021 for (NetworkInfo netInfo: ni) {
4022 log("netInfo=" + netInfo.toString());
4023 }
4024 } else {
4025 log("no network info ni=null");
4026 }
4027 }
4028
4029 /**
4030 * Sleep for a few seconds then return.
4031 * @param seconds
4032 */
4033 private static void sleep(int seconds) {
4034 try {
4035 Thread.sleep(seconds * 1000);
4036 } catch (InterruptedException e) {
4037 e.printStackTrace();
4038 }
4039 }
4040
4041 public boolean hasIPv4Address(LinkProperties lp) {
4042 return lp.hasIPv4Address();
4043 }
4044
4045 // Not implemented in LinkProperties, do it here.
4046 public boolean hasIPv6Address(LinkProperties lp) {
4047 for (LinkAddress address : lp.getLinkAddresses()) {
4048 if (address.getAddress() instanceof Inet6Address) {
4049 return true;
4050 }
4051 }
4052 return false;
4053 }
4054
4055 private void log(String s) {
4056 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4057 }
4058 }
4059
4060 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4061
4062 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
4063 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
4064
4065 Resources r = Resources.getSystem();
4066 NotificationManager notificationManager = (NotificationManager) mContext
4067 .getSystemService(Context.NOTIFICATION_SERVICE);
4068
4069 if (visible) {
4070 CharSequence title;
4071 CharSequence details;
4072 int icon;
4073 switch (networkInfo.getType()) {
4074 case ConnectivityManager.TYPE_WIFI:
4075 log("setNotificationVisible: TYPE_WIFI");
4076 title = r.getString(R.string.wifi_available_sign_in, 0);
4077 details = r.getString(R.string.network_available_sign_in_detailed,
4078 networkInfo.getExtraInfo());
4079 icon = R.drawable.stat_notify_wifi_in_range;
4080 break;
4081 case ConnectivityManager.TYPE_MOBILE:
4082 case ConnectivityManager.TYPE_MOBILE_HIPRI:
4083 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
4084 title = r.getString(R.string.network_available_sign_in, 0);
4085 // TODO: Change this to pull from NetworkInfo once a printable
4086 // name has been added to it
4087 details = mTelephonyManager.getNetworkOperatorName();
4088 icon = R.drawable.stat_notify_rssi_in_range;
4089 break;
4090 default:
4091 log("setNotificationVisible: other type=" + networkInfo.getType());
4092 title = r.getString(R.string.network_available_sign_in, 0);
4093 details = r.getString(R.string.network_available_sign_in_detailed,
4094 networkInfo.getExtraInfo());
4095 icon = R.drawable.stat_notify_rssi_in_range;
4096 break;
4097 }
4098
4099 Notification notification = new Notification();
4100 notification.when = 0;
4101 notification.icon = icon;
4102 notification.flags = Notification.FLAG_AUTO_CANCEL;
4103 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4104 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4105 Intent.FLAG_ACTIVITY_NEW_TASK);
4106 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4107 notification.tickerText = title;
4108 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4109
4110 log("setNotificaitionVisible: notify notificaiton=" + notification);
4111 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4112 } else {
4113 log("setNotificaitionVisible: cancel");
4114 notificationManager.cancel(NOTIFICATION_ID, 1);
4115 }
4116 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
4117 }
4118
4119 private String getProvisioningUrl() {
4120 String url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Savillec118d7e2013-07-10 23:00:07 -07004121 log("getProvisioningUrl: mobile_provisioning_url=" + url);
Wink Saville32506bc2013-06-29 21:10:57 -07004122
Wink Savillec118d7e2013-07-10 23:00:07 -07004123 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville32506bc2013-06-29 21:10:57 -07004124 if (!TextUtils.isEmpty(url)) {
Wink Savillec118d7e2013-07-10 23:00:07 -07004125 String phoneNumber = mTelephonyManager.getLine1Number();
4126 if (TextUtils.isEmpty(phoneNumber)) {
4127 phoneNumber = "0000000000";
4128 }
Wink Saville32506bc2013-06-29 21:10:57 -07004129 url = String.format(url,
4130 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4131 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savillec118d7e2013-07-10 23:00:07 -07004132 phoneNumber /* Phone numer */);
Wink Saville32506bc2013-06-29 21:10:57 -07004133 }
4134
Wink Saville32506bc2013-06-29 21:10:57 -07004135 return url;
4136 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07004137
4138 private void onUserStart(int userId) {
4139 synchronized(mVpns) {
4140 Vpn userVpn = mVpns.get(userId);
4141 if (userVpn != null) {
4142 loge("Starting user already has a VPN");
4143 return;
4144 }
4145 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4146 mVpns.put(userId, userVpn);
4147 userVpn.startMonitoring(mContext, mTrackerHandler);
4148 }
4149 }
4150
4151 private void onUserStop(int userId) {
4152 synchronized(mVpns) {
4153 Vpn userVpn = mVpns.get(userId);
4154 if (userVpn == null) {
4155 loge("Stopping user has no VPN");
4156 return;
4157 }
4158 mVpns.delete(userId);
4159 }
4160 }
4161
4162 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4163 @Override
4164 public void onReceive(Context context, Intent intent) {
4165 final String action = intent.getAction();
4166 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4167 if (userId == UserHandle.USER_NULL) return;
4168
4169 if (Intent.ACTION_USER_STARTING.equals(action)) {
4170 onUserStart(userId);
4171 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4172 onUserStop(userId);
4173 }
4174 }
4175 };
The Android Open Source Project28527d22009-03-03 19:31:44 -08004176}