blob: 979bccd9a1b1357ca8ebbe9855c2440674ba10e9 [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 Saville690cb182013-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 Sharkeyf2e722a2012-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 Sharkeyf2e722a2012-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 Sheriffba8388b2012-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 Saville690cb182013-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 Saville690cb182013-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 Saville690cb182013-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 Greenwalt030e1d32012-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 Sharkey5663b6e2012-09-06 17:54:29 -070086import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070087import android.os.RemoteException;
Wink Saville690cb182013-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 Hackbornbc55bd12012-08-29 18:32:08 -070092import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080093import android.provider.Settings;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -070094import android.security.Credentials;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -070095import android.security.KeyStore;
Wink Saville690cb182013-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 Brubakerccae0d32013-06-14 11:16:51 -0700100import android.util.SparseArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800101
Wink Saville690cb182013-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 Sharkeyc2a8e402012-08-24 11:17:25 -0700105import com.android.internal.net.VpnProfile;
Wink Saville690cb182013-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 Sharkeyf58fbae2012-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 Spurlock4ba7e412013-06-24 14:20:23 -0400111import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti5355abd2013-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 Sharkeyf2e722a2012-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 Brubakerccae0d32013-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 Saville690cb182013-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 Saville690cb182013-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 Saville690cb182013-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 Sharkey02e14d92012-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 Sharkey02e14d92012-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 Saville690cb182013-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 Sharkeyf2e722a2012-08-25 00:05:46 -0700175 private KeyStore mKeyStore;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700176
Chad Brubakerccae0d32013-06-14 11:16:51 -0700177 @GuardedBy("mVpns")
178 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700179 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700180
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700181 private boolean mLockdownEnabled;
182 private LockdownVpnTracker mLockdownTracker;
183
Lorenzo Colitti5355abd2013-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 Sheriffba8388b2012-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 Falkdc919012011-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 Saville3e866722013-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 Greenwaltd44340d2013-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 Sharkeyf2e722a2012-08-25 00:05:46 -0700318 private static final int EVENT_VPN_STATE_CHANGED = 14;
319
Wink Saville690cb182013-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 Greenwaltda77cb12013-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 Spurlock4ba7e412013-06-24 14:20:23 -0400379 private DataConnectionStats mDataConnectionStats;
Wink Saville690cb182013-06-29 21:10:57 -0700380 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
381
382 TelephonyManager mTelephonyManager;
John Spurlock4ba7e412013-06-24 14:20:23 -0400383
Wink Saville9564f2b2013-07-16 17:16:37 -0700384 // We only want one checkMobileProvisioning after booting.
385 volatile boolean mFirstProvisioningCheckStarted = false;
386
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700387 public ConnectivityService(Context context, INetworkManagementService netd,
388 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700389 // Currently, omitting a NetworkFactory will create one internally
390 // TODO: create here when we have cleaner WiMAX support
391 this(context, netd, statsService, policyManager, null);
392 }
393
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700394 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700395 INetworkStatsService statsService, INetworkPolicyManager policyManager,
396 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800397 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800398
Wink Saville775aad62010-09-02 19:23:52 -0700399 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
400 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700401 mHandler = new InternalHandler(handlerThread.getLooper());
402 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700403
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700404 if (netFactory == null) {
405 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
406 }
407
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800408 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800409 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
410 String id = Settings.Secure.getString(context.getContentResolver(),
411 Settings.Secure.ANDROID_ID);
412 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700413 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800414 SystemProperties.set("net.hostname", name);
415 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800416 }
417
Robert Greenwalt94daa182010-09-01 11:34:05 -0700418 // read our default dns server ip
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700419 String dns = Settings.Global.getString(context.getContentResolver(),
420 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700421 if (dns == null || dns.length() == 0) {
422 dns = context.getResources().getString(
423 com.android.internal.R.string.config_default_dns_server);
424 }
425 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800426 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
427 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800428 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700429 }
430
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700431 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700432 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700433 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700434 mKeyStore = KeyStore.getInstance();
Wink Saville690cb182013-06-29 21:10:57 -0700435 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700436
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700437 try {
438 mPolicyManager.registerListener(mPolicyListener);
439 } catch (RemoteException e) {
440 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700441 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700442 }
443
444 final PowerManager powerManager = (PowerManager) context.getSystemService(
445 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700446 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
447 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
448 com.android.internal.R.integer.config_networkTransitionTimeout);
449
Robert Greenwalt2034b912009-08-12 16:08:25 -0700450 mNetTrackers = new NetworkStateTracker[
451 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700452 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700453
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700454 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700455 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700456
Robert Greenwalt2034b912009-08-12 16:08:25 -0700457 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700458 String[] raStrings = context.getResources().getStringArray(
459 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700460 for (String raString : raStrings) {
461 RadioAttributes r = new RadioAttributes(raString);
462 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800463 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700464 continue;
465 }
466 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800467 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700468 r.mType);
469 continue;
470 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700471 mRadioAttributes[r.mType] = r;
472 }
473
Wink Saville23ee8db2013-04-23 14:26:51 -0700474 // TODO: What is the "correct" way to do determine if this is a wifi only device?
475 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
476 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700477 String[] naStrings = context.getResources().getStringArray(
478 com.android.internal.R.array.networkAttributes);
479 for (String naString : naStrings) {
480 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700481 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700482 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800483 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700484 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700485 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700486 }
Wink Saville23ee8db2013-04-23 14:26:51 -0700487 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
488 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
489 n.type);
490 continue;
491 }
Wink Savillef2a62832011-04-07 14:23:45 -0700492 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800493 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700494 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700495 continue;
496 }
Wink Savillef2a62832011-04-07 14:23:45 -0700497 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800498 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700499 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700500 continue;
501 }
Wink Savillef2a62832011-04-07 14:23:45 -0700502 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700503 mNetworksDefined++;
504 } catch(Exception e) {
505 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700506 }
507 }
508
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700509 mProtectedNetworks = new ArrayList<Integer>();
510 int[] protectedNetworks = context.getResources().getIntArray(
511 com.android.internal.R.array.config_protectedNetworks);
512 for (int p : protectedNetworks) {
513 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
514 mProtectedNetworks.add(p);
515 } else {
516 if (DBG) loge("Ignoring protectedNetwork " + p);
517 }
518 }
519
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700520 // high priority first
521 mPriorityList = new int[mNetworksDefined];
522 {
523 int insertionPoint = mNetworksDefined-1;
524 int currentLowest = 0;
525 int nextLowest = 0;
526 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700527 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700528 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700529 if (na.priority < currentLowest) continue;
530 if (na.priority > currentLowest) {
531 if (na.priority < nextLowest || nextLowest == 0) {
532 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700533 }
534 continue;
535 }
Wink Savillef2a62832011-04-07 14:23:45 -0700536 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700537 }
538 currentLowest = nextLowest;
539 nextLowest = 0;
540 }
541 }
542
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800543 // Update mNetworkPreference according to user mannually first then overlay config.xml
544 mNetworkPreference = getPersistedNetworkPreference();
545 if (mNetworkPreference == -1) {
546 for (int n : mPriorityList) {
547 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
548 mNetworkPreference = n;
549 break;
550 }
551 }
552 if (mNetworkPreference == -1) {
553 throw new IllegalStateException(
554 "You should set at least one default Network in config.xml!");
555 }
556 }
557
Mattias Falkdc919012011-08-23 14:15:13 +0200558 mNetRequestersPids =
559 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700560 for (int i : mPriorityList) {
Mattias Falkdc919012011-08-23 14:15:13 +0200561 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700562 }
563
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500564 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700565
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700566 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
567 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700568
569 // Create and start trackers for hard-coded networks
570 for (int targetNetworkType : mPriorityList) {
571 final NetworkConfig config = mNetConfigs[targetNetworkType];
572 final NetworkStateTracker tracker;
573 try {
574 tracker = netFactory.createTracker(targetNetworkType, config);
575 mNetTrackers[targetNetworkType] = tracker;
576 } catch (IllegalArgumentException e) {
577 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
578 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700579 continue;
580 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700581
582 tracker.startMonitoring(context, mTrackerHandler);
583 if (config.isDefault()) {
584 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800585 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700586 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800587
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700588 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700589 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700590 mTethering.getTetherableWifiRegexs().length != 0 ||
591 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700592 mTethering.getUpstreamIfaceTypes().length != 0);
Chad Brubakerccae0d32013-06-14 11:16:51 -0700593 //set up the listener for user state for creating user VPNs
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800594
Chad Brubakerccae0d32013-06-14 11:16:51 -0700595 IntentFilter intentFilter = new IntentFilter();
596 intentFilter.addAction(Intent.ACTION_USER_STARTING);
597 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
598 mContext.registerReceiverAsUser(
599 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900600 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
601
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700602 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700603 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700604 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900605 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700606 } catch (RemoteException e) {
607 loge("Error registering observer :" + e);
608 }
609
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700610 if (DBG) {
611 mInetLog = new ArrayList();
612 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700613
614 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
615 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800616
Irfan Sheriff2e617a72012-09-20 09:32:41 -0700617 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800618 loadGlobalProxy();
John Spurlock4ba7e412013-06-24 14:20:23 -0400619
620 mDataConnectionStats = new DataConnectionStats(mContext);
621 mDataConnectionStats.startMonitoring();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800622 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700623
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700624 /**
625 * Factory that creates {@link NetworkStateTracker} instances using given
626 * {@link NetworkConfig}.
627 */
628 public interface NetworkFactory {
629 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
630 }
631
632 private static class DefaultNetworkFactory implements NetworkFactory {
633 private final Context mContext;
634 private final Handler mTrackerHandler;
635
636 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
637 mContext = context;
638 mTrackerHandler = trackerHandler;
639 }
640
641 @Override
642 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
643 switch (config.radio) {
644 case TYPE_WIFI:
645 return new WifiStateTracker(targetNetworkType, config.name);
646 case TYPE_MOBILE:
647 return new MobileDataStateTracker(targetNetworkType, config.name);
648 case TYPE_DUMMY:
649 return new DummyDataStateTracker(targetNetworkType, config.name);
650 case TYPE_BLUETOOTH:
651 return BluetoothTetheringDataTracker.getInstance();
652 case TYPE_WIMAX:
653 return makeWimaxStateTracker(mContext, mTrackerHandler);
654 case TYPE_ETHERNET:
655 return EthernetDataTracker.getInstance();
656 default:
657 throw new IllegalArgumentException(
658 "Trying to create a NetworkStateTracker for an unknown radio type: "
659 + config.radio);
660 }
661 }
662 }
663
664 /**
665 * Loads external WiMAX library and registers as system service, returning a
666 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
667 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
668 */
669 private static NetworkStateTracker makeWimaxStateTracker(
670 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700671 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900672 DexClassLoader wimaxClassLoader;
673 Class wimaxStateTrackerClass = null;
674 Class wimaxServiceClass = null;
675 Class wimaxManagerClass;
676 String wimaxJarLocation;
677 String wimaxLibLocation;
678 String wimaxManagerClassName;
679 String wimaxServiceClassName;
680 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800681
tk.mun093f55c2011-10-13 22:51:57 +0900682 NetworkStateTracker wimaxStateTracker = null;
683
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700684 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900685 com.android.internal.R.bool.config_wimaxEnabled);
686
687 if (isWimaxEnabled) {
688 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700689 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900690 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700691 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900692 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700693 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900694 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700695 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900696 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700697 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900698 com.android.internal.R.string.config_wimaxStateTrackerClassname);
699
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800700 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900701 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700702 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900703 wimaxLibLocation, ClassLoader.getSystemClassLoader());
704
705 try {
706 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
707 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
708 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
709 } catch (ClassNotFoundException ex) {
710 loge("Exception finding Wimax classes: " + ex.toString());
711 return null;
712 }
713 } catch(Resources.NotFoundException ex) {
714 loge("Wimax Resources does not exist!!! ");
715 return null;
716 }
717
718 try {
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800719 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900720
721 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
722 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700723 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
724 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900725
726 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
727 (new Class[] {Context.class, wimaxStateTrackerClass});
728 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700729 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900730 wmxSrvConst.setAccessible(false);
731
732 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
733
734 } catch(Exception ex) {
735 loge("Exception creating Wimax classes: " + ex.toString());
736 return null;
737 }
738 } else {
739 loge("Wimax is not enabled or not added to the network attributes!!! ");
740 return null;
741 }
742
743 return wimaxStateTracker;
744 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700745
The Android Open Source Project28527d22009-03-03 19:31:44 -0800746 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700747 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800748 * @param preference the new preference
749 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700750 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800751 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700752
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700753 mHandler.sendMessage(
754 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800755 }
756
757 public int getNetworkPreference() {
758 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700759 int preference;
760 synchronized(this) {
761 preference = mNetworkPreference;
762 }
763 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800764 }
765
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700766 private void handleSetNetworkPreference(int preference) {
767 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700768 mNetConfigs[preference] != null &&
769 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700770 if (mNetworkPreference != preference) {
771 final ContentResolver cr = mContext.getContentResolver();
Jeff Brown87272712012-09-25 15:03:20 -0700772 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700773 synchronized(this) {
774 mNetworkPreference = preference;
775 }
776 enforcePreference();
777 }
778 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800779 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700780
Wink Saville4f0de1e2011-08-04 15:01:58 -0700781 private int getConnectivityChangeDelay() {
782 final ContentResolver cr = mContext.getContentResolver();
783
784 /** Check system properties for the default value then use secure settings value, if any. */
785 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700786 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
787 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
788 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700789 defaultDelay);
790 }
791
The Android Open Source Project28527d22009-03-03 19:31:44 -0800792 private int getPersistedNetworkPreference() {
793 final ContentResolver cr = mContext.getContentResolver();
794
Jeff Brown87272712012-09-25 15:03:20 -0700795 final int networkPrefSetting = Settings.Global
796 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800797
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800798 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800799 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700800
The Android Open Source Project28527d22009-03-03 19:31:44 -0800801 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700802 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800803 * In this method, we only tear down a non-preferred network. Establishing
804 * a connection to the preferred network is taken care of when we handle
805 * the disconnect event from the non-preferred network
806 * (see {@link #handleDisconnect(NetworkInfo)}).
807 */
808 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700809 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800810 return;
811
Robert Greenwalt2034b912009-08-12 16:08:25 -0700812 if (!mNetTrackers[mNetworkPreference].isAvailable())
813 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800814
Robert Greenwalt2034b912009-08-12 16:08:25 -0700815 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700816 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700817 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700818 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800819 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700820 " in enforcePreference");
821 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700822 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800823 }
824 }
825 }
826
827 private boolean teardown(NetworkStateTracker netTracker) {
828 if (netTracker.teardown()) {
829 netTracker.setTeardownRequested(true);
830 return true;
831 } else {
832 return false;
833 }
834 }
835
836 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700837 * Check if UID should be blocked from using the network represented by the
838 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700839 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700840 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
841 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700842
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700843 final boolean networkCostly;
844 final int uidRules;
845 synchronized (mRulesLock) {
846 networkCostly = mMeteredIfaces.contains(iface);
847 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700848 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700849
850 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
851 return true;
852 }
853
854 // no restrictive rules; network is visible
855 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700856 }
857
858 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700859 * Return a filtered {@link NetworkInfo}, potentially marked
860 * {@link DetailedState#BLOCKED} based on
861 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700862 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700863 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
864 NetworkInfo info = tracker.getNetworkInfo();
865 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700866 // network is blocked; clone and override state
867 info = new NetworkInfo(info);
868 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700869 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700870 if (mLockdownTracker != null) {
871 info = mLockdownTracker.augmentNetworkInfo(info);
872 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700873 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700874 }
875
876 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800877 * Return NetworkInfo for the active (i.e., connected) network interface.
878 * It is assumed that at most one network is active at a time. If more
879 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700880 * @return the info for the active network, or {@code null} if none is
881 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800882 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700883 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800884 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700885 enforceAccessPermission();
886 final int uid = Binder.getCallingUid();
887 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800888 }
889
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700890 public NetworkInfo getActiveNetworkInfoUnfiltered() {
891 enforceAccessPermission();
892 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
893 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
894 if (tracker != null) {
895 return tracker.getNetworkInfo();
896 }
897 }
898 return null;
899 }
900
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700901 @Override
902 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
903 enforceConnectivityInternalPermission();
904 return getNetworkInfo(mActiveDefaultNetwork, uid);
905 }
906
907 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800908 public NetworkInfo getNetworkInfo(int networkType) {
909 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700910 final int uid = Binder.getCallingUid();
911 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800912 }
913
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700914 private NetworkInfo getNetworkInfo(int networkType, int uid) {
915 NetworkInfo info = null;
916 if (isNetworkTypeValid(networkType)) {
917 final NetworkStateTracker tracker = mNetTrackers[networkType];
918 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700919 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700920 }
921 }
922 return info;
923 }
924
925 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800926 public NetworkInfo[] getAllNetworkInfo() {
927 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700928 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700929 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700930 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700931 for (NetworkStateTracker tracker : mNetTrackers) {
932 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700933 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700934 }
935 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800936 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700937 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800938 }
939
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700940 @Override
941 public boolean isNetworkSupported(int networkType) {
942 enforceAccessPermission();
943 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
944 }
945
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700946 /**
947 * Return LinkProperties for the active (i.e., connected) default
948 * network interface. It is assumed that at most one default network
949 * is active at a time. If more than one is active, it is indeterminate
950 * which will be returned.
951 * @return the ip properties for the active network, or {@code null} if
952 * none is active
953 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700954 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700955 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700956 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700957 }
958
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700959 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700960 public LinkProperties getLinkProperties(int networkType) {
961 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700962 if (isNetworkTypeValid(networkType)) {
963 final NetworkStateTracker tracker = mNetTrackers[networkType];
964 if (tracker != null) {
965 return tracker.getLinkProperties();
966 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700967 }
968 return null;
969 }
970
Jeff Sharkey21062e72011-05-28 20:56:34 -0700971 @Override
972 public NetworkState[] getAllNetworkState() {
973 enforceAccessPermission();
974 final int uid = Binder.getCallingUid();
975 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700976 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700977 for (NetworkStateTracker tracker : mNetTrackers) {
978 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700979 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700980 result.add(new NetworkState(
981 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
982 }
983 }
984 }
985 return result.toArray(new NetworkState[result.size()]);
986 }
987
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700988 private NetworkState getNetworkStateUnchecked(int networkType) {
989 if (isNetworkTypeValid(networkType)) {
990 final NetworkStateTracker tracker = mNetTrackers[networkType];
991 if (tracker != null) {
992 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
993 tracker.getLinkCapabilities());
994 }
995 }
996 return null;
997 }
998
999 @Override
1000 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1001 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001002
1003 final long token = Binder.clearCallingIdentity();
1004 try {
1005 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1006 if (state != null) {
1007 try {
1008 return mPolicyManager.getNetworkQuotaInfo(state);
1009 } catch (RemoteException e) {
1010 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001011 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001012 return null;
1013 } finally {
1014 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001015 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001016 }
1017
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001018 @Override
1019 public boolean isActiveNetworkMetered() {
1020 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001021 final long token = Binder.clearCallingIdentity();
1022 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001023 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001024 } finally {
1025 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001026 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001027 }
1028
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001029 private boolean isNetworkMeteredUnchecked(int networkType) {
1030 final NetworkState state = getNetworkStateUnchecked(networkType);
1031 if (state != null) {
1032 try {
1033 return mPolicyManager.isNetworkMetered(state);
1034 } catch (RemoteException e) {
1035 }
1036 }
1037 return false;
1038 }
1039
The Android Open Source Project28527d22009-03-03 19:31:44 -08001040 public boolean setRadios(boolean turnOn) {
1041 boolean result = true;
1042 enforceChangePermission();
1043 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001044 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001045 }
1046 return result;
1047 }
1048
1049 public boolean setRadio(int netType, boolean turnOn) {
1050 enforceChangePermission();
1051 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1052 return false;
1053 }
1054 NetworkStateTracker tracker = mNetTrackers[netType];
1055 return tracker != null && tracker.setRadio(turnOn);
1056 }
1057
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001058 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1059 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001060 public void interfaceClassDataActivityChanged(String label, boolean active) {
1061 int deviceType = Integer.parseInt(label);
1062 sendDataActivityBroadcast(deviceType, active);
1063 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001064 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001065
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001066 /**
1067 * Used to notice when the calling process dies so we can self-expire
1068 *
1069 * Also used to know if the process has cleaned up after itself when
1070 * our auto-expire timer goes off. The timer has a link to an object.
1071 *
1072 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001073 private class FeatureUser implements IBinder.DeathRecipient {
1074 int mNetworkType;
1075 String mFeature;
1076 IBinder mBinder;
1077 int mPid;
1078 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001079 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001080
1081 FeatureUser(int type, String feature, IBinder binder) {
1082 super();
1083 mNetworkType = type;
1084 mFeature = feature;
1085 mBinder = binder;
1086 mPid = getCallingPid();
1087 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001088 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001089
Robert Greenwalt2034b912009-08-12 16:08:25 -07001090 try {
1091 mBinder.linkToDeath(this, 0);
1092 } catch (RemoteException e) {
1093 binderDied();
1094 }
1095 }
1096
1097 void unlinkDeathRecipient() {
1098 mBinder.unlinkToDeath(this, 0);
1099 }
1100
1101 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001102 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001103 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1104 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001105 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001106 }
1107
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001108 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001109 if (VDBG) {
1110 log("ConnectivityService FeatureUser expire(" +
1111 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1112 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1113 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001114 stopUsingNetworkFeature(this, false);
1115 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001116
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001117 public boolean isSameUser(FeatureUser u) {
1118 if (u == null) return false;
1119
1120 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1121 }
1122
1123 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1124 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1125 TextUtils.equals(mFeature, feature)) {
1126 return true;
1127 }
1128 return false;
1129 }
1130
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001131 public String toString() {
1132 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1133 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1134 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001135 }
1136
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001137 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001138 public int startUsingNetworkFeature(int networkType, String feature,
1139 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001140 long startTime = 0;
1141 if (DBG) {
1142 startTime = SystemClock.elapsedRealtime();
1143 }
Wink Savillea7d56572011-09-21 11:05:43 -07001144 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001145 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1146 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001147 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001148 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001149 try {
1150 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1151 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001152 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001153 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001154
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001155 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001156
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001157 // TODO - move this into individual networktrackers
1158 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001159
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001160 if (mLockdownEnabled) {
1161 // Since carrier APNs usually aren't available from VPN
1162 // endpoint, mark them as unavailable.
1163 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1164 }
1165
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001166 if (mProtectedNetworks.contains(usedNetworkType)) {
1167 enforceConnectivityInternalPermission();
1168 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001169
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001170 // if UID is restricted, don't allow them to bring up metered APNs
1171 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1172 final int uidRules;
1173 synchronized (mRulesLock) {
1174 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1175 }
1176 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001177 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001178 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001179
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001180 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1181 if (network != null) {
1182 Integer currentPid = new Integer(getCallingPid());
1183 if (usedNetworkType != networkType) {
1184 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001185
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001186 if (ni.isAvailable() == false) {
1187 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1188 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001189 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001190 } else {
1191 // else make the attempt anyway - probably giving REQUEST_STARTED below
1192 if (DBG) {
1193 log("special network not available, but try anyway ni=" +
1194 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001195 }
1196 }
1197 }
1198
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001199 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001200
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001201 synchronized(this) {
1202 boolean addToList = true;
1203 if (restoreTimer < 0) {
1204 // In case there is no timer is specified for the feature,
1205 // make sure we don't add duplicate entry with the same request.
1206 for (FeatureUser u : mFeatureUsers) {
1207 if (u.isSameUser(f)) {
1208 // Duplicate user is found. Do not add.
1209 addToList = false;
1210 break;
1211 }
1212 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001213 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001214
1215 if (addToList) mFeatureUsers.add(f);
1216 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1217 // this gets used for per-pid dns when connected
1218 mNetRequestersPids[usedNetworkType].add(currentPid);
1219 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001220 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001221
1222 if (restoreTimer >= 0) {
1223 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1224 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1225 }
1226
1227 if ((ni.isConnectedOrConnecting() == true) &&
1228 !network.isTeardownRequested()) {
1229 if (ni.isConnected() == true) {
1230 final long token = Binder.clearCallingIdentity();
1231 try {
1232 // add the pid-specific dns
1233 handleDnsConfigurationChange(usedNetworkType);
1234 if (VDBG) log("special network already active");
1235 } finally {
1236 Binder.restoreCallingIdentity(token);
1237 }
Wink Saville64e3f782012-07-10 12:37:54 -07001238 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001239 }
1240 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001241 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001242 }
1243
1244 // check if the radio in play can make another contact
1245 // assume if cannot for now
1246
1247 if (DBG) {
1248 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1249 feature);
1250 }
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001251 if (network.reconnect()) {
1252 return PhoneConstants.APN_REQUEST_STARTED;
1253 } else {
1254 return PhoneConstants.APN_REQUEST_FAILED;
1255 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001256 } else {
1257 // need to remember this unsupported request so we respond appropriately on stop
1258 synchronized(this) {
1259 mFeatureUsers.add(f);
1260 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1261 // this gets used for per-pid dns when connected
1262 mNetRequestersPids[usedNetworkType].add(currentPid);
1263 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001264 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001265 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001266 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001267 }
Wink Saville64e3f782012-07-10 12:37:54 -07001268 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001269 } finally {
1270 if (DBG) {
1271 final long execTime = SystemClock.elapsedRealtime() - startTime;
1272 if (execTime > 250) {
1273 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1274 } else {
1275 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1276 }
1277 }
1278 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001279 }
1280
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001281 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001282 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001283 enforceChangePermission();
1284
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001285 int pid = getCallingPid();
1286 int uid = getCallingUid();
1287
1288 FeatureUser u = null;
1289 boolean found = false;
1290
1291 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001292 for (FeatureUser x : mFeatureUsers) {
1293 if (x.isSameUser(pid, uid, networkType, feature)) {
1294 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001295 found = true;
1296 break;
1297 }
1298 }
1299 }
1300 if (found && u != null) {
1301 // stop regardless of how many other time this proc had called start
1302 return stopUsingNetworkFeature(u, true);
1303 } else {
1304 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001305 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001306 return 1;
1307 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001308 }
1309
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001310 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1311 int networkType = u.mNetworkType;
1312 String feature = u.mFeature;
1313 int pid = u.mPid;
1314 int uid = u.mUid;
1315
1316 NetworkStateTracker tracker = null;
1317 boolean callTeardown = false; // used to carry our decision outside of sync block
1318
Wink Savillea7d56572011-09-21 11:05:43 -07001319 if (VDBG) {
1320 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001321 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001322
The Android Open Source Project28527d22009-03-03 19:31:44 -08001323 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001324 if (DBG) {
1325 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1326 ", net is invalid");
1327 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001328 return -1;
1329 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001330
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001331 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1332 // sync block
1333 synchronized(this) {
1334 // check if this process still has an outstanding start request
1335 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001336 if (VDBG) {
1337 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1338 ", ignoring");
1339 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001340 return 1;
1341 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001342 u.unlinkDeathRecipient();
1343 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1344 // If we care about duplicate requests, check for that here.
1345 //
1346 // This is done to support the extension of a request - the app
1347 // can request we start the network feature again and renew the
1348 // auto-shutoff delay. Normal "stop" calls from the app though
1349 // do not pay attention to duplicate requests - in effect the
1350 // API does not refcount and a single stop will counter multiple starts.
1351 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001352 for (FeatureUser x : mFeatureUsers) {
1353 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001354 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001355 return 1;
1356 }
1357 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001358 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001359
repo syncf5de5572011-07-29 23:55:49 -07001360 // TODO - move to individual network trackers
1361 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1362
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001363 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001364 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001365 if (DBG) {
1366 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1367 " no known tracker for used net type " + usedNetworkType);
1368 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001369 return -1;
1370 }
1371 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001372 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001373 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt17900092013-02-12 17:18:25 -08001374
1375 final long token = Binder.clearCallingIdentity();
1376 try {
1377 reassessPidDns(pid, true);
1378 } finally {
1379 Binder.restoreCallingIdentity(token);
1380 }
Mattias Falkdc919012011-08-23 14:15:13 +02001381 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001382 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001383 if (VDBG) {
1384 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1385 " others still using it");
1386 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001387 return 1;
1388 }
1389 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001390 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001391 if (DBG) {
1392 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1393 " not a known feature - dropping");
1394 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001395 }
1396 }
Wink Savillea7d56572011-09-21 11:05:43 -07001397
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001398 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001399 if (DBG) {
1400 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1401 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001402 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001403 return 1;
1404 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001405 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001406 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001407 }
1408
1409 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001410 * @deprecated use requestRouteToHostAddress instead
1411 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001412 * Ensure that a network route exists to deliver traffic to the specified
1413 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001414 * @param networkType the type of the network over which traffic to the
1415 * specified host is to be routed
1416 * @param hostAddress the IP address of the host to which the route is
1417 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001418 * @return {@code true} on success, {@code false} on failure
1419 */
1420 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001421 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1422
1423 if (inetAddress == null) {
1424 return false;
1425 }
1426
1427 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1428 }
1429
1430 /**
1431 * Ensure that a network route exists to deliver traffic to the specified
1432 * host via the specified network interface.
1433 * @param networkType the type of the network over which traffic to the
1434 * specified host is to be routed
1435 * @param hostAddress the IP address of the host to which the route is
1436 * desired
1437 * @return {@code true} on success, {@code false} on failure
1438 */
1439 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001440 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001441 if (mProtectedNetworks.contains(networkType)) {
1442 enforceConnectivityInternalPermission();
1443 }
1444
The Android Open Source Project28527d22009-03-03 19:31:44 -08001445 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001446 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001447 return false;
1448 }
1449 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriffba8388b2012-08-16 12:49:23 -07001450 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001451
Irfan Sheriffba8388b2012-08-16 12:49:23 -07001452 if (tracker == null || (netState != DetailedState.CONNECTED &&
1453 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001454 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001455 if (VDBG) {
Wink Saville690cb182013-06-29 21:10:57 -07001456 log("requestRouteToHostAddress on down network "
1457 + "(" + networkType + ") - dropped"
1458 + " tracker=" + tracker
1459 + " netState=" + netState
1460 + " isTeardownRequested="
1461 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001462 }
1463 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001464 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001465 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001466 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001467 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001468 LinkProperties lp = tracker.getLinkProperties();
Wink Saville690cb182013-06-29 21:10:57 -07001469 boolean ok = addRouteToAddress(lp, addr);
1470 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1471 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001472 } catch (UnknownHostException e) {
1473 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1474 } finally {
1475 Binder.restoreCallingIdentity(token);
1476 }
Wink Saville690cb182013-06-29 21:10:57 -07001477 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001478 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001479 }
1480
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001481 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001482 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001483 }
1484
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001485 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001486 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001487 }
1488
Robert Greenwalt98107422011-07-22 11:55:33 -07001489 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001490 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001491 }
1492
1493 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001494 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001495 }
1496
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001497 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1498 boolean toDefaultTable) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001499 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001500 if (bestRoute == null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001501 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001502 } else {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001503 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001504 if (bestRoute.getGateway().equals(addr)) {
1505 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001506 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001507 } else {
1508 // if we will connect to this through another route, add a direct route
1509 // to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001510 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001511 }
1512 }
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001513 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001514 }
1515
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001516 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1517 boolean toDefaultTable) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001518 if ((lp == null) || (r == null)) {
1519 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001520 return false;
1521 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001522
1523 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001524 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001525 return false;
1526 }
1527
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001528 String ifaceName = r.getInterface();
1529 if(ifaceName == null) {
1530 loge("Error modifying route - no interface name");
1531 return false;
1532 }
Robert Greenwalt24bc5342013-04-11 13:48:16 -07001533 if (r.hasGateway()) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001534 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001535 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001536 if (bestRoute.getGateway().equals(r.getGateway())) {
1537 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001538 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001539 } else {
1540 // if we will connect to our gateway through another route, add a direct
1541 // route to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001542 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1543 bestRoute.getGateway(),
1544 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001545 }
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001546 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001547 }
1548 }
1549 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001550 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001551 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001552 if (toDefaultTable) {
1553 mAddedRoutes.add(r); // only track default table - only one apps can effect
1554 mNetd.addRoute(ifaceName, r);
1555 } else {
1556 mNetd.addSecondaryRoute(ifaceName, r);
1557 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001558 } catch (Exception e) {
1559 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001560 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001561 return false;
1562 }
1563 } else {
1564 // if we remove this one and there are no more like it, then refcount==0 and
1565 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001566 if (toDefaultTable) {
1567 mAddedRoutes.remove(r);
1568 if (mAddedRoutes.contains(r) == false) {
1569 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1570 try {
1571 mNetd.removeRoute(ifaceName, r);
1572 } catch (Exception e) {
1573 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001574 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001575 return false;
1576 }
1577 } else {
1578 if (VDBG) log("not removing " + r + " as it's still in use");
1579 }
1580 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001581 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001582 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001583 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001584 } catch (Exception e) {
1585 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001586 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001587 return false;
1588 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001589 }
1590 }
1591 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001592 }
1593
1594 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001595 * @see ConnectivityManager#getMobileDataEnabled()
1596 */
1597 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001598 // TODO: This detail should probably be in DataConnectionTracker's
1599 // which is where we store the value and maybe make this
1600 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001601 enforceAccessPermission();
Jeff Sharkey9ee49b32012-09-26 15:54:06 -07001602 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1603 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001604 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001605 return retVal;
1606 }
1607
Robert Greenwalt34848c02011-03-25 13:09:25 -07001608 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001609 enforceConnectivityInternalPermission();
1610
Robert Greenwalt34848c02011-03-25 13:09:25 -07001611 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1612 (met ? ENABLED : DISABLED), networkType));
1613 }
1614
1615 private void handleSetDependencyMet(int networkType, boolean met) {
1616 if (mNetTrackers[networkType] != null) {
1617 if (DBG) {
1618 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1619 }
1620 mNetTrackers[networkType].setDependencyMet(met);
1621 }
1622 }
1623
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001624 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1625 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001626 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001627 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001628 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001629 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001630 }
1631
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001632 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001633 // skip update when we've already applied rules
1634 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1635 if (oldRules == uidRules) return;
1636
1637 mUidRules.put(uid, uidRules);
1638 }
1639
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001640 // TODO: notify UID when it has requested targeted updates
1641 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001642
1643 @Override
1644 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001645 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001646 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001647 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001648 }
1649
1650 synchronized (mRulesLock) {
1651 mMeteredIfaces.clear();
1652 for (String iface : meteredIfaces) {
1653 mMeteredIfaces.add(iface);
1654 }
1655 }
1656 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001657
1658 @Override
1659 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1660 // caller is NPMS, since we only register with them
1661 if (LOGD_RULES) {
1662 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1663 }
1664
1665 // kick off connectivity change broadcast for active network, since
1666 // global background policy change is radical.
1667 final int networkType = mActiveDefaultNetwork;
1668 if (isNetworkTypeValid(networkType)) {
1669 final NetworkStateTracker tracker = mNetTrackers[networkType];
1670 if (tracker != null) {
1671 final NetworkInfo info = tracker.getNetworkInfo();
1672 if (info != null && info.isConnected()) {
1673 sendConnectedBroadcast(info);
1674 }
1675 }
1676 }
1677 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001678 };
1679
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001680 /**
1681 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1682 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001683 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001684 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001685 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001686
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001687 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001688 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001689 }
1690
1691 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001692 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001693 if (VDBG) {
1694 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001695 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001696 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1697 }
tk.mun5eee1042012-01-06 10:43:52 +09001698 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1699 if (VDBG) {
1700 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1701 }
1702 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1703 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001704 }
1705
1706 @Override
1707 public void setPolicyDataEnable(int networkType, boolean enabled) {
1708 // only someone like NPMS should only be calling us
1709 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1710
1711 mHandler.sendMessage(mHandler.obtainMessage(
1712 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1713 }
1714
1715 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1716 if (isNetworkTypeValid(networkType)) {
1717 final NetworkStateTracker tracker = mNetTrackers[networkType];
1718 if (tracker != null) {
1719 tracker.setPolicyDataEnable(enabled);
1720 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001721 }
1722 }
1723
The Android Open Source Project28527d22009-03-03 19:31:44 -08001724 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001725 mContext.enforceCallingOrSelfPermission(
1726 android.Manifest.permission.ACCESS_NETWORK_STATE,
1727 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001728 }
1729
1730 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001731 mContext.enforceCallingOrSelfPermission(
1732 android.Manifest.permission.CHANGE_NETWORK_STATE,
1733 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001734 }
1735
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001736 // TODO Make this a special check when it goes public
1737 private void enforceTetherChangePermission() {
1738 mContext.enforceCallingOrSelfPermission(
1739 android.Manifest.permission.CHANGE_NETWORK_STATE,
1740 "ConnectivityService");
1741 }
1742
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001743 private void enforceTetherAccessPermission() {
1744 mContext.enforceCallingOrSelfPermission(
1745 android.Manifest.permission.ACCESS_NETWORK_STATE,
1746 "ConnectivityService");
1747 }
1748
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001749 private void enforceConnectivityInternalPermission() {
1750 mContext.enforceCallingOrSelfPermission(
1751 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1752 "ConnectivityService");
1753 }
1754
Chad Brubaker31de0b62013-07-11 13:29:30 -07001755 private void enforceMarkNetworkSocketPermission() {
1756 //Media server special case
1757 if (Binder.getCallingUid() == Process.MEDIA_UID) {
1758 return;
1759 }
1760 mContext.enforceCallingOrSelfPermission(
1761 android.Manifest.permission.MARK_NETWORK_SOCKET,
1762 "ConnectivityService");
1763 }
1764
The Android Open Source Project28527d22009-03-03 19:31:44 -08001765 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001766 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1767 * network, we ignore it. If it is for the active network, we send out a
1768 * broadcast. But first, we check whether it might be possible to connect
1769 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001770 * @param info the {@code NetworkInfo} for the network
1771 */
1772 private void handleDisconnect(NetworkInfo info) {
1773
Robert Greenwalt2034b912009-08-12 16:08:25 -07001774 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001775
Robert Greenwalt2034b912009-08-12 16:08:25 -07001776 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai92e03a72012-06-28 15:26:19 -07001777
1778 // Remove idletimer previously setup in {@code handleConnect}
1779 removeDataActivityTracking(prevNetType);
1780
The Android Open Source Project28527d22009-03-03 19:31:44 -08001781 /*
1782 * If the disconnected network is not the active one, then don't report
1783 * this as a loss of connectivity. What probably happened is that we're
1784 * getting the disconnect for a network that we explicitly disabled
1785 * in accordance with network preference policies.
1786 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001787 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkdc919012011-08-23 14:15:13 +02001788 List<Integer> pids = mNetRequestersPids[prevNetType];
1789 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001790 // will remove them because the net's no longer connected
1791 // need to do this now as only now do we know the pids and
1792 // can properly null things that are no longer referenced.
1793 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001794 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001795 }
1796
The Android Open Source Project28527d22009-03-03 19:31:44 -08001797 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07001798 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001799 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001800 if (info.isFailover()) {
1801 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1802 info.setFailover(false);
1803 }
1804 if (info.getReason() != null) {
1805 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1806 }
1807 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001808 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1809 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001810 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001811
Robert Greenwalt34848c02011-03-25 13:09:25 -07001812 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001813 tryFailover(prevNetType);
1814 if (mActiveDefaultNetwork != -1) {
1815 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001816 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1817 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001818 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001819 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1820 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001821 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001822 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001823
1824 // Reset interface if no other connections are using the same interface
1825 boolean doReset = true;
1826 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1827 if (linkProperties != null) {
1828 String oldIface = linkProperties.getInterfaceName();
1829 if (TextUtils.isEmpty(oldIface) == false) {
1830 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1831 if (networkStateTracker == null) continue;
1832 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1833 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1834 LinkProperties l = networkStateTracker.getLinkProperties();
1835 if (l == null) continue;
1836 if (oldIface.equals(l.getInterfaceName())) {
1837 doReset = false;
1838 break;
1839 }
1840 }
1841 }
1842 }
1843 }
1844
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001845 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001846 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001847
Jeff Sharkey971cd162011-08-29 16:02:57 -07001848 final Intent immediateIntent = new Intent(intent);
1849 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1850 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001851 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001852 /*
1853 * If the failover network is already connected, then immediately send
1854 * out a followup broadcast indicating successful failover
1855 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001856 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001857 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1858 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001859 }
1860 }
1861
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001862 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001863 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001864 * If this is a default network, check if other defaults are available.
1865 * Try to reconnect on all available and let them hash it out when
1866 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001867 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001868 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001869 if (mActiveDefaultNetwork == prevNetType) {
1870 mActiveDefaultNetwork = -1;
1871 }
1872
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001873 // don't signal a reconnect for anything lower or equal priority than our
1874 // current connected default
1875 // TODO - don't filter by priority now - nice optimization but risky
1876// int currentPriority = -1;
1877// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001878// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001879// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001880 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001881 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001882 if (mNetConfigs[checkType] == null) continue;
1883 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001884 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001885
1886// Enabling the isAvailable() optimization caused mobile to not get
1887// selected if it was in the middle of error handling. Specifically
1888// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1889// would not be available and we wouldn't get connected to anything.
1890// So removing the isAvailable() optimization below for now. TODO: This
1891// optimization should work and we need to investigate why it doesn't work.
1892// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1893// complete before it is really complete.
1894// if (!mNetTrackers[checkType].isAvailable()) continue;
1895
Robert Greenwalt34848c02011-03-25 13:09:25 -07001896// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001897
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001898 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1899 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1900 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1901 checkInfo.setFailover(true);
1902 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001903 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001904 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001905 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001906 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001907 }
1908
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001909 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08001910 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07001911 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1912 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001913 }
1914
Wink Saville4f0de1e2011-08-04 15:01:58 -07001915 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001916 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1917 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001918 }
1919
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001920 private void sendInetConditionBroadcast(NetworkInfo info) {
1921 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1922 }
1923
Wink Saville4f0de1e2011-08-04 15:01:58 -07001924 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001925 if (mLockdownTracker != null) {
1926 info = mLockdownTracker.augmentNetworkInfo(info);
1927 }
1928
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001929 Intent intent = new Intent(bcastType);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07001930 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001931 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001932 if (info.isFailover()) {
1933 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1934 info.setFailover(false);
1935 }
1936 if (info.getReason() != null) {
1937 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1938 }
1939 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001940 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1941 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001942 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001943 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001944 return intent;
1945 }
1946
1947 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1948 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1949 }
1950
1951 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1952 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001953 }
1954
Haoyu Baib5da5752012-06-20 14:29:57 -07001955 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1956 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1957 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1958 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07001959 final long ident = Binder.clearCallingIdentity();
1960 try {
1961 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1962 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1963 } finally {
1964 Binder.restoreCallingIdentity(ident);
1965 }
Haoyu Baib5da5752012-06-20 14:29:57 -07001966 }
1967
The Android Open Source Project28527d22009-03-03 19:31:44 -08001968 /**
1969 * Called when an attempt to fail over to another network has failed.
1970 * @param info the {@link NetworkInfo} for the failed network
1971 */
1972 private void handleConnectionFailure(NetworkInfo info) {
1973 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001974
Robert Greenwalt2034b912009-08-12 16:08:25 -07001975 String reason = info.getReason();
1976 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001977
Robert Greenwalte981bc52010-10-08 16:35:52 -07001978 String reasonText;
1979 if (reason == null) {
1980 reasonText = ".";
1981 } else {
1982 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001983 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001984 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001985
1986 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07001987 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001988 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001989 if (getActiveNetworkInfo() == null) {
1990 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1991 }
1992 if (reason != null) {
1993 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1994 }
1995 if (extraInfo != null) {
1996 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1997 }
1998 if (info.isFailover()) {
1999 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2000 info.setFailover(false);
2001 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002002
Robert Greenwalt34848c02011-03-25 13:09:25 -07002003 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002004 tryFailover(info.getType());
2005 if (mActiveDefaultNetwork != -1) {
2006 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002007 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2008 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002009 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002010 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2011 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002012 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08002013
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07002014 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002015
2016 final Intent immediateIntent = new Intent(intent);
2017 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2018 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002019 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002020 /*
2021 * If the failover network is already connected, then immediately send
2022 * out a followup broadcast indicating successful failover
2023 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002024 if (mActiveDefaultNetwork != -1) {
2025 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002026 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002027 }
2028
2029 private void sendStickyBroadcast(Intent intent) {
2030 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002031 if (!mSystemReady) {
2032 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002033 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002034 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002035 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002036 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002037 }
2038
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002039 final long ident = Binder.clearCallingIdentity();
2040 try {
2041 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2042 } finally {
2043 Binder.restoreCallingIdentity(ident);
2044 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002045 }
2046 }
2047
Wink Saville4f0de1e2011-08-04 15:01:58 -07002048 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2049 if (delayMs <= 0) {
2050 sendStickyBroadcast(intent);
2051 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002052 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002053 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2054 + intent.getAction());
2055 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002056 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2057 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2058 }
2059 }
2060
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002061 void systemReady() {
2062 synchronized(this) {
2063 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002064 if (mInitialBroadcast != null) {
Dianne Hackbornbc55bd12012-08-29 18:32:08 -07002065 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002066 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002067 }
2068 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002069 // load the global proxy at startup
2070 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002071
2072 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2073 // for user to unlock device.
2074 if (!updateLockdownVpn()) {
2075 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2076 mContext.registerReceiver(mUserPresentReceiver, filter);
2077 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002078 }
2079
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002080 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2081 @Override
2082 public void onReceive(Context context, Intent intent) {
2083 // Try creating lockdown tracker, since user present usually means
2084 // unlocked keystore.
2085 if (updateLockdownVpn()) {
2086 mContext.unregisterReceiver(this);
2087 }
2088 }
2089 };
2090
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002091 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2092 if ((type != mNetworkPreference &&
2093 mNetConfigs[mActiveDefaultNetwork].priority >
2094 mNetConfigs[type].priority) ||
2095 mNetworkPreference == mActiveDefaultNetwork) return false;
2096 return true;
2097 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002098
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002099 private void handleConnect(NetworkInfo info) {
2100 final int newNetType = info.getType();
2101
2102 setupDataActivityTracking(newNetType);
Haoyu Bai92e03a72012-06-28 15:26:19 -07002103
The Android Open Source Project28527d22009-03-03 19:31:44 -08002104 // snapshot isFailover, because sendConnectedBroadcast() resets it
2105 boolean isFailover = info.isFailover();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002106 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002107 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002108
Robert Greenwalt2034b912009-08-12 16:08:25 -07002109 // if this is a default net and other default is running
2110 // kill the one not preferred
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002111 if (mNetConfigs[newNetType].isDefault()) {
2112 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2113 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002114 // tear down the other
2115 NetworkStateTracker otherNet =
2116 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002117 if (DBG) {
2118 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002119 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002120 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002121 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002122 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002123 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002124 return;
2125 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002126 } else {
2127 // don't accept this one
2128 if (VDBG) {
2129 log("Not broadcasting CONNECT_ACTION " +
2130 "to torn down network " + info.getTypeName());
2131 }
2132 teardown(thisNet);
2133 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002134 }
2135 }
2136 synchronized (ConnectivityService.this) {
2137 // have a new default network, release the transition wakelock in a second
2138 // if it's held. The second pause is to allow apps to reconnect over the
2139 // new network
2140 if (mNetTransitionWakeLock.isHeld()) {
2141 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002142 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002143 mNetTransitionWakeLockSerialNumber, 0),
2144 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002145 }
2146 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002147 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002148 // this will cause us to come up initially as unconnected and switching
2149 // to connected after our normal pause unless somebody reports us as reall
2150 // disconnected
2151 mDefaultInetConditionPublished = 0;
2152 mDefaultConnectionSequence++;
2153 mInetConditionChangeInFlight = false;
2154 // Don't do this - if we never sign in stay, grey
2155 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002156 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002157 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002158 updateNetworkSettings(thisNet);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002159 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002160 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002161
2162 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002163 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002164 try {
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002165 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002166 } catch (RemoteException e) {
2167 // ignored; service lives in system_server
2168 }
2169 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002170 }
2171
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002172 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2173 if (DBG) log("Captive portal check " + info);
2174 int type = info.getType();
2175 final NetworkStateTracker thisNet = mNetTrackers[type];
2176 if (mNetConfigs[type].isDefault()) {
2177 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2178 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2179 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002180 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002181 return;
2182 } else {
2183 if (DBG) log("Tear down low priority net " + info.getTypeName());
2184 teardown(thisNet);
2185 return;
2186 }
2187 }
2188 }
2189
2190 thisNet.captivePortalCheckComplete();
2191 }
2192
2193 /** @hide */
2194 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002195 enforceConnectivityInternalPermission();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002196 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002197 }
2198
The Android Open Source Project28527d22009-03-03 19:31:44 -08002199 /**
Haoyu Bai92e03a72012-06-28 15:26:19 -07002200 * Setup data activity tracking for the given network interface.
2201 *
2202 * Every {@code setupDataActivityTracking} should be paired with a
2203 * {@link removeDataActivityTracking} for cleanup.
2204 */
2205 private void setupDataActivityTracking(int type) {
2206 final NetworkStateTracker thisNet = mNetTrackers[type];
2207 final String iface = thisNet.getLinkProperties().getInterfaceName();
2208
2209 final int timeout;
2210
2211 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brown87272712012-09-25 15:03:20 -07002212 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2213 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002214 0);
2215 // Canonicalize mobile network type
2216 type = ConnectivityManager.TYPE_MOBILE;
2217 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brown87272712012-09-25 15:03:20 -07002218 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2219 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002220 0);
2221 } else {
2222 // do not track any other networks
2223 timeout = 0;
2224 }
2225
2226 if (timeout > 0 && iface != null) {
2227 try {
2228 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2229 } catch (RemoteException e) {
2230 }
2231 }
2232 }
2233
2234 /**
2235 * Remove data activity tracking when network disconnects.
2236 */
2237 private void removeDataActivityTracking(int type) {
2238 final NetworkStateTracker net = mNetTrackers[type];
2239 final String iface = net.getLinkProperties().getInterfaceName();
2240
2241 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2242 ConnectivityManager.TYPE_WIFI == type)) {
2243 try {
2244 // the call fails silently if no idletimer setup for this interface
2245 mNetd.removeIdleTimer(iface);
2246 } catch (RemoteException e) {
2247 }
2248 }
2249 }
2250
2251 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002252 * After a change in the connectivity state of a network. We're mainly
2253 * concerned with making sure that the list of DNS servers is set up
2254 * according to which networks are connected, and ensuring that the
2255 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002256 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002257 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002258 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2259
The Android Open Source Project28527d22009-03-03 19:31:44 -08002260 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002261 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002262 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002263 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002264 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002265
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002266 LinkProperties curLp = mCurrentLinkProperties[netType];
2267 LinkProperties newLp = null;
2268
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002269 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002270 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002271 if (VDBG) {
2272 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2273 " doReset=" + doReset + " resetMask=" + resetMask +
2274 "\n curLp=" + curLp +
2275 "\n newLp=" + newLp);
2276 }
2277
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002278 if (curLp != null) {
2279 if (curLp.isIdenticalInterfaceName(newLp)) {
2280 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2281 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2282 for (LinkAddress linkAddr : car.removed) {
2283 if (linkAddr.getAddress() instanceof Inet4Address) {
2284 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2285 }
2286 if (linkAddr.getAddress() instanceof Inet6Address) {
2287 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2288 }
Wink Saville051a6642011-07-13 13:44:13 -07002289 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002290 if (DBG) {
2291 log("handleConnectivityChange: addresses changed" +
2292 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2293 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002294 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002295 } else {
2296 if (DBG) {
2297 log("handleConnectivityChange: address are the same reset per doReset" +
2298 " linkProperty[" + netType + "]:" +
2299 " resetMask=" + resetMask);
2300 }
Wink Saville051a6642011-07-13 13:44:13 -07002301 }
2302 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002303 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002304 if (DBG) {
2305 log("handleConnectivityChange: interface not not equivalent reset both" +
2306 " linkProperty[" + netType + "]:" +
2307 " resetMask=" + resetMask);
2308 }
Wink Saville051a6642011-07-13 13:44:13 -07002309 }
Wink Saville051a6642011-07-13 13:44:13 -07002310 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002311 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002312 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002313 }
2314 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002315 if (VDBG) {
2316 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2317 " doReset=" + doReset + " resetMask=" + resetMask +
2318 "\n curLp=" + curLp +
2319 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002320 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002321 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002322 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07002323 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002324
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002325 if (resetMask != 0 || resetDns) {
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002326 if (curLp != null) {
2327 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002328 if (TextUtils.isEmpty(iface) == false) {
2329 if (resetMask != 0) {
2330 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2331 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002332
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002333 // Tell VPN the interface is down. It is a temporary
2334 // but effective fix to make VPN aware of the change.
2335 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07002336 synchronized(mVpns) {
2337 for (int i = 0; i < mVpns.size(); i++) {
2338 mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2339 }
2340 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002341 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002342 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002343 if (resetDns) {
2344 flushVmDnsCache();
2345 if (VDBG) log("resetting DNS cache for " + iface);
2346 try {
2347 mNetd.flushInterfaceDnsCache(iface);
2348 } catch (Exception e) {
2349 // never crash - catch them all
2350 if (DBG) loge("Exception resetting dns cache: " + e);
2351 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002352 }
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002353 } else {
2354 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002355 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002356 }
2357 }
2358 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002359
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002360 // Update 464xlat state.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002361 NetworkStateTracker tracker = mNetTrackers[netType];
2362 if (mClat.requiresClat(netType, tracker)) {
Lorenzo Colitti7e5624b2013-03-28 14:13:43 +09002363 // If the connection was previously using clat, but is not using it now, stop the clat
2364 // daemon. Normally, this happens automatically when the connection disconnects, but if
2365 // the disconnect is not reported, or if the connection's LinkProperties changed for
2366 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2367 // still be running. If it's not running, then stopping it is a no-op.
2368 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2369 mClat.stopClat();
2370 }
2371 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002372 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2373 mClat.startClat(tracker);
2374 } else {
2375 mClat.stopClat();
2376 }
2377 }
2378
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002379 // TODO: Temporary notifying upstread change to Tethering.
2380 // @see bug/4455071
2381 /** Notify TetheringService if interface name has been changed. */
2382 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002383 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002384 if (isTetheringSupported()) {
2385 mTethering.handleTetherIfaceChange();
2386 }
2387 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002388 }
2389
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002390 /**
2391 * Add and remove routes using the old properties (null if not previously connected),
2392 * new properties (null if becoming disconnected). May even be double null, which
2393 * is a noop.
2394 * Uses isLinkDefault to determine if default routes should be set or conversely if
2395 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002396 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002397 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002398 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2399 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002400 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002401 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2402 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002403 if (curLp != null) {
2404 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002405 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002406 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002407 } else if (newLp != null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002408 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002409 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002410 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002411
Robert Greenwalt8d777252011-08-15 12:31:55 -07002412 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2413
Robert Greenwalt98107422011-07-22 11:55:33 -07002414 for (RouteInfo r : routeDiff.removed) {
2415 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002416 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2417 }
2418 if (isLinkDefault == false) {
2419 // remove from a secondary route table
2420 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002421 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002422 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002423
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002424 if (!isLinkDefault) {
2425 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002426 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002427 // routes changed - remove all old dns entries and add new
2428 if (curLp != null) {
2429 for (InetAddress oldDns : curLp.getDnses()) {
2430 removeRouteToAddress(curLp, oldDns);
2431 }
2432 }
2433 if (newLp != null) {
2434 for (InetAddress newDns : newLp.getDnses()) {
2435 addRouteToAddress(newLp, newDns);
2436 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002437 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002438 } else {
2439 // no change in routes, check for change in dns themselves
2440 for (InetAddress oldDns : dnsDiff.removed) {
2441 removeRouteToAddress(curLp, oldDns);
2442 }
2443 for (InetAddress newDns : dnsDiff.added) {
2444 addRouteToAddress(newLp, newDns);
2445 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002446 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002447 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002448
2449 for (RouteInfo r : routeDiff.added) {
2450 if (isLinkDefault || ! r.isDefaultRoute()) {
2451 addRoute(newLp, r, TO_DEFAULT_TABLE);
2452 } else {
2453 // add to a secondary route table
2454 addRoute(newLp, r, TO_SECONDARY_TABLE);
2455
2456 // many radios add a default route even when we don't want one.
2457 // remove the default route unless somebody else has asked for it
2458 String ifaceName = newLp.getInterfaceName();
2459 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2460 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2461 try {
2462 mNetd.removeRoute(ifaceName, r);
2463 } catch (Exception e) {
2464 // never crash - catch them all
2465 if (DBG) loge("Exception trying to remove a route: " + e);
2466 }
2467 }
2468 }
2469 }
2470
Robert Greenwalt8d777252011-08-15 12:31:55 -07002471 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002472 }
2473
2474
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002475 /**
2476 * Reads the network specific TCP buffer sizes from SystemProperties
2477 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2478 * wide use
2479 */
Robert Greenwalt26744a52013-02-15 10:56:35 -08002480 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002481 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002482 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002483
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002484 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002485 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002486
2487 // Setting to default values so we won't be stuck to previous values
2488 key = "net.tcp.buffersize.default";
2489 bufferSizes = SystemProperties.get(key);
2490 }
2491
2492 // Set values in kernel
2493 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002494 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002495 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002496 + "] which comes from [" + key + "]");
2497 }
2498 setBufferSize(bufferSizes);
2499 }
2500 }
2501
2502 /**
2503 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2504 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2505 *
2506 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2507 * writeMin, writeInitial, writeMax"
2508 */
2509 private void setBufferSize(String bufferSizes) {
2510 try {
2511 String[] values = bufferSizes.split(",");
2512
2513 if (values.length == 6) {
2514 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002515 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2516 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2517 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2518 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2519 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2520 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002521 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002522 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002523 }
2524 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002525 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002526 }
2527 }
2528
Robert Greenwalt2034b912009-08-12 16:08:25 -07002529 /**
2530 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2531 * on the highest priority active net which this process requested.
2532 * If there aren't any, clear it out
2533 */
Mattias Falkdc919012011-08-23 14:15:13 +02002534 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002535 {
Mattias Falkdc919012011-08-23 14:15:13 +02002536 if (VDBG) log("reassessPidDns for pid " + pid);
2537 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002538 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002539 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002540 continue;
2541 }
2542 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002543 if (nt.getNetworkInfo().isConnected() &&
2544 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002545 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002546 if (p == null) continue;
Mattias Falkdc919012011-08-23 14:15:13 +02002547 if (mNetRequestersPids[i].contains(myPid)) {
2548 try {
2549 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2550 } catch (Exception e) {
2551 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002552 }
Mattias Falkdc919012011-08-23 14:15:13 +02002553 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002554 }
2555 }
2556 }
2557 // nothing found - delete
Mattias Falkdc919012011-08-23 14:15:13 +02002558 try {
2559 mNetd.clearDnsInterfaceForPid(pid);
2560 } catch (Exception e) {
2561 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002562 }
2563 }
2564
Mattias Falkdc919012011-08-23 14:15:13 +02002565 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002566 /*
2567 * Tell the VMs to toss their DNS caches
2568 */
2569 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2570 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002571 /*
2572 * Connectivity events can happen before boot has completed ...
2573 */
2574 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002575 final long ident = Binder.clearCallingIdentity();
2576 try {
2577 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2578 } finally {
2579 Binder.restoreCallingIdentity(ident);
2580 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002581 }
2582
Chia-chi Yehcc844502011-07-14 18:01:57 -07002583 // Caller must grab mDnsLock.
Mattias Falkdc919012011-08-23 14:15:13 +02002584 private void updateDnsLocked(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002585 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002586 int last = 0;
2587 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkdc919012011-08-23 14:15:13 +02002588 dnses = new ArrayList();
2589 dnses.add(mDefaultDns);
2590 if (DBG) {
2591 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002592 }
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002593 }
2594
Mattias Falkdc919012011-08-23 14:15:13 +02002595 try {
2596 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Robert Greenwaltd44340d2013-02-11 15:25:10 -08002597 for (InetAddress dns : dnses) {
2598 ++last;
2599 String key = "net.dns" + last;
2600 String value = dns.getHostAddress();
2601 SystemProperties.set(key, value);
2602 }
2603 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2604 String key = "net.dns" + i;
2605 SystemProperties.set(key, "");
2606 }
2607 mNumDnsEntries = last;
Mattias Falkdc919012011-08-23 14:15:13 +02002608 } catch (Exception e) {
2609 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002610 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002611 }
2612
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002613 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002614 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002615 NetworkStateTracker nt = mNetTrackers[netType];
2616 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002617 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002618 if (p == null) return;
2619 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002620 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002621 String network = nt.getNetworkInfo().getTypeName();
2622 synchronized (mDnsLock) {
2623 if (!mDnsOverridden) {
Mattias Falkdc919012011-08-23 14:15:13 +02002624 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalt94daa182010-09-01 11:34:05 -07002625 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002626 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002627 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002628 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002629 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt0bc6c962012-11-09 10:52:27 -08002630 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002631 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002632 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002633 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002634 // set per-pid dns for attached secondary nets
Mattias Falkdc919012011-08-23 14:15:13 +02002635 List<Integer> pids = mNetRequestersPids[netType];
2636 for (Integer pid : pids) {
2637 try {
2638 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2639 } catch (Exception e) {
2640 Slog.e(TAG, "exception setting interface for pid: " + e);
2641 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002642 }
2643 }
Mattias Falkdc919012011-08-23 14:15:13 +02002644 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002645 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002646 }
2647
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002648 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002649 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2650 NETWORK_RESTORE_DELAY_PROP_NAME);
2651 if(restoreDefaultNetworkDelayStr != null &&
2652 restoreDefaultNetworkDelayStr.length() != 0) {
2653 try {
2654 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2655 } catch (NumberFormatException e) {
2656 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002657 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002658 // if the system property isn't set, use the value for the apn type
2659 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2660
2661 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2662 (mNetConfigs[networkType] != null)) {
2663 ret = mNetConfigs[networkType].restoreTime;
2664 }
2665 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002666 }
2667
2668 @Override
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002669 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2670 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002671 if (mContext.checkCallingOrSelfPermission(
2672 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002673 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002674 pw.println("Permission Denial: can't dump ConnectivityService " +
2675 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2676 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002677 return;
2678 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002679
2680 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002681 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002682 for (int i = 0; i < mNetTrackers.length; i++) {
2683 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002684 if (nst != null) {
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002685 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2686 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002687 if (nst.getNetworkInfo().isConnected()) {
2688 pw.println("Active network: " + nst.getNetworkInfo().
2689 getTypeName());
2690 }
2691 pw.println(nst.getNetworkInfo());
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002692 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002693 pw.println(nst);
2694 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002695 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002696 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002697 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002698
2699 pw.println("Network Requester Pids:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002700 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002701 for (int net : mPriorityList) {
2702 String pidString = net + ": ";
Mattias Falkdc919012011-08-23 14:15:13 +02002703 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002704 pidString = pidString + pid.toString() + ", ";
2705 }
2706 pw.println(pidString);
2707 }
2708 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002709 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002710
2711 pw.println("FeatureUsers:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002712 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002713 for (Object requester : mFeatureUsers) {
2714 pw.println(requester.toString());
2715 }
2716 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002717 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002718
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002719 synchronized (this) {
2720 pw.println("NetworkTranstionWakeLock is currently " +
2721 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2722 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2723 }
2724 pw.println();
2725
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002726 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002727
2728 if (mInetLog != null) {
2729 pw.println();
2730 pw.println("Inet condition reports:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002731 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002732 for(int i = 0; i < mInetLog.size(); i++) {
2733 pw.println(mInetLog.get(i));
2734 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002735 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002736 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002737 }
2738
Robert Greenwalt2034b912009-08-12 16:08:25 -07002739 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002740 private class NetworkStateTrackerHandler extends Handler {
2741 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002742 super(looper);
2743 }
2744
The Android Open Source Project28527d22009-03-03 19:31:44 -08002745 @Override
2746 public void handleMessage(Message msg) {
2747 NetworkInfo info;
2748 switch (msg.what) {
2749 case NetworkStateTracker.EVENT_STATE_CHANGED:
2750 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002751 int type = info.getType();
2752 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002753
Wink Savillea7d56572011-09-21 11:05:43 -07002754 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2755 (state == NetworkInfo.State.DISCONNECTED)) {
2756 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002757 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002758 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002759 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002760
Wink Saville9564f2b2013-07-16 17:16:37 -07002761 // After booting we'll check once for mobile provisioning
2762 // if we've provisioned by and connected.
2763 if (!mFirstProvisioningCheckStarted
2764 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2765 Settings.Global.DEVICE_PROVISIONED, 0))
2766 && (state == NetworkInfo.State.CONNECTED)) {
2767 log("check provisioning after booting");
2768 mFirstProvisioningCheckStarted = true;
2769 checkMobileProvisioning(true, CheckMp.MAX_TIMEOUT_MS, null);
2770 }
2771
Jeff Sharkeybde32692012-11-09 15:57:02 -08002772 EventLogTags.writeConnectivityStateChanged(
2773 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002774
2775 if (info.getDetailedState() ==
2776 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002777 handleConnectionFailure(info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002778 } else if (info.getDetailedState() ==
2779 DetailedState.CAPTIVE_PORTAL_CHECK) {
2780 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002781 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002782 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002783 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002784 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002785 // the logic here is, handle SUSPENDED the same as
2786 // DISCONNECTED. The only difference being we are
2787 // broadcasting an intent with NetworkInfo that's
2788 // suspended. This allows the applications an
2789 // opportunity to handle DISCONNECTED and SUSPENDED
2790 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002791 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002792 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002793 handleConnect(info);
2794 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002795 if (mLockdownTracker != null) {
2796 mLockdownTracker.onNetworkInfoChanged(info);
2797 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002798 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002799 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002800 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002801 // TODO: Temporary allowing network configuration
2802 // change not resetting sockets.
2803 // @see bug/4455071
2804 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002805 break;
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07002806 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2807 info = (NetworkInfo) msg.obj;
2808 type = info.getType();
2809 updateNetworkSettings(mNetTrackers[type]);
2810 break;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002811 }
2812 }
2813 }
2814
2815 private class InternalHandler extends Handler {
2816 public InternalHandler(Looper looper) {
2817 super(looper);
2818 }
2819
2820 @Override
2821 public void handleMessage(Message msg) {
2822 NetworkInfo info;
2823 switch (msg.what) {
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002824 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002825 String causedBy = null;
2826 synchronized (ConnectivityService.this) {
2827 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2828 mNetTransitionWakeLock.isHeld()) {
2829 mNetTransitionWakeLock.release();
2830 causedBy = mNetTransitionWakeLockCausedBy;
2831 }
2832 }
2833 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002834 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002835 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002836 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002837 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002838 FeatureUser u = (FeatureUser)msg.obj;
2839 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002840 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002841 case EVENT_INET_CONDITION_CHANGE:
2842 {
2843 int netType = msg.arg1;
2844 int condition = msg.arg2;
2845 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002846 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002847 }
2848 case EVENT_INET_CONDITION_HOLD_END:
2849 {
2850 int netType = msg.arg1;
2851 int sequence = msg.arg2;
Wink Saville3e866722013-01-31 00:30:13 +00002852 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002853 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002854 }
2855 case EVENT_SET_NETWORK_PREFERENCE:
2856 {
2857 int preference = msg.arg1;
2858 handleSetNetworkPreference(preference);
2859 break;
2860 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002861 case EVENT_SET_MOBILE_DATA:
2862 {
2863 boolean enabled = (msg.arg1 == ENABLED);
2864 handleSetMobileData(enabled);
2865 break;
2866 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002867 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2868 {
2869 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002870 break;
2871 }
2872 case EVENT_SET_DEPENDENCY_MET:
2873 {
2874 boolean met = (msg.arg1 == ENABLED);
2875 handleSetDependencyMet(msg.arg2, met);
2876 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002877 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002878 case EVENT_RESTORE_DNS:
2879 {
2880 if (mActiveDefaultNetwork != -1) {
2881 handleDnsConfigurationChange(mActiveDefaultNetwork);
2882 }
2883 break;
2884 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002885 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2886 {
2887 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002888 sendStickyBroadcast(intent);
2889 break;
2890 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002891 case EVENT_SET_POLICY_DATA_ENABLE: {
2892 final int networkType = msg.arg1;
2893 final boolean enabled = msg.arg2 == ENABLED;
2894 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002895 break;
2896 }
2897 case EVENT_VPN_STATE_CHANGED: {
2898 if (mLockdownTracker != null) {
2899 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2900 }
2901 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07002902 }
Wink Saville690cb182013-06-29 21:10:57 -07002903 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2904 int tag = mEnableFailFastMobileDataTag.get();
2905 if (msg.arg1 == tag) {
2906 MobileDataStateTracker mobileDst =
2907 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2908 if (mobileDst != null) {
2909 mobileDst.setEnableFailFastMobileData(msg.arg2);
2910 }
2911 } else {
2912 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2913 + " != tag:" + tag);
2914 }
2915 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002916 }
2917 }
2918 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002919
2920 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002921 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002922 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002923
2924 if (isTetheringSupported()) {
2925 return mTethering.tether(iface);
2926 } else {
2927 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2928 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002929 }
2930
2931 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002932 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002933 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002934
2935 if (isTetheringSupported()) {
2936 return mTethering.untether(iface);
2937 } else {
2938 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2939 }
2940 }
2941
2942 // javadoc from interface
2943 public int getLastTetherError(String iface) {
2944 enforceTetherAccessPermission();
2945
2946 if (isTetheringSupported()) {
2947 return mTethering.getLastTetherError(iface);
2948 } else {
2949 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2950 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002951 }
2952
2953 // TODO - proper iface API for selection by property, inspection, etc
2954 public String[] getTetherableUsbRegexs() {
2955 enforceTetherAccessPermission();
2956 if (isTetheringSupported()) {
2957 return mTethering.getTetherableUsbRegexs();
2958 } else {
2959 return new String[0];
2960 }
2961 }
2962
2963 public String[] getTetherableWifiRegexs() {
2964 enforceTetherAccessPermission();
2965 if (isTetheringSupported()) {
2966 return mTethering.getTetherableWifiRegexs();
2967 } else {
2968 return new String[0];
2969 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002970 }
2971
Danica Chang96567052010-08-11 14:54:43 -07002972 public String[] getTetherableBluetoothRegexs() {
2973 enforceTetherAccessPermission();
2974 if (isTetheringSupported()) {
2975 return mTethering.getTetherableBluetoothRegexs();
2976 } else {
2977 return new String[0];
2978 }
2979 }
2980
Mike Lockwooded4a1742011-07-19 13:04:47 -07002981 public int setUsbTethering(boolean enable) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002982 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07002983 if (isTetheringSupported()) {
2984 return mTethering.setUsbTethering(enable);
2985 } else {
2986 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2987 }
2988 }
2989
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002990 // TODO - move iface listing, queries, etc to new module
2991 // javadoc from interface
2992 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002993 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002994 return mTethering.getTetherableIfaces();
2995 }
2996
2997 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002998 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002999 return mTethering.getTetheredIfaces();
3000 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003001
Jeff Sharkey300f08f2011-09-16 01:52:49 -07003002 @Override
3003 public String[] getTetheredIfacePairs() {
3004 enforceTetherAccessPermission();
3005 return mTethering.getTetheredIfacePairs();
3006 }
3007
Robert Greenwalt4283ded2010-03-02 17:25:02 -08003008 public String[] getTetheringErroredIfaces() {
3009 enforceTetherAccessPermission();
3010 return mTethering.getErroredIfaces();
3011 }
3012
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003013 // if ro.tether.denied = true we default to no tethering
3014 // gservices could set the secure setting to 1 though to enable it on a build where it
3015 // had previously been turned off.
3016 public boolean isTetheringSupported() {
3017 enforceTetherAccessPermission();
3018 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brown87272712012-09-25 15:03:20 -07003019 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3020 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08003021 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003022 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003023
3024 // An API NetworkStateTrackers can call when they lose their network.
3025 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3026 // whichever happens first. The timer is started by the first caller and not
3027 // restarted by subsequent callers.
3028 public void requestNetworkTransitionWakelock(String forWhom) {
3029 enforceConnectivityInternalPermission();
3030 synchronized (this) {
3031 if (mNetTransitionWakeLock.isHeld()) return;
3032 mNetTransitionWakeLockSerialNumber++;
3033 mNetTransitionWakeLock.acquire();
3034 mNetTransitionWakeLockCausedBy = forWhom;
3035 }
3036 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003037 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003038 mNetTransitionWakeLockSerialNumber, 0),
3039 mNetTransitionWakeLockTimeout);
3040 return;
3041 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003042
Robert Greenwalt986c7412010-09-08 15:24:47 -07003043 // 100 percent is full good, 0 is full bad.
3044 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003045 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003046 mContext.enforceCallingOrSelfPermission(
3047 android.Manifest.permission.STATUS_BAR,
3048 "ConnectivityService");
3049
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003050 if (DBG) {
3051 int pid = getCallingPid();
3052 int uid = getCallingUid();
3053 String s = pid + "(" + uid + ") reports inet is " +
3054 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3055 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3056 mInetLog.add(s);
3057 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3058 mInetLog.remove(0);
3059 }
3060 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003061 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003062 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3063 }
3064
3065 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003066 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003067 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003068 return;
3069 }
3070 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003071 if (DBG) log("handleInetConditionChange: net=" + netType +
3072 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003073 return;
3074 }
Wink Savillea7d56572011-09-21 11:05:43 -07003075 if (VDBG) {
3076 log("handleInetConditionChange: net=" +
3077 netType + ", condition=" + condition +
Wink Saville3e866722013-01-31 00:30:13 +00003078 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003079 }
Wink Saville3e866722013-01-31 00:30:13 +00003080 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003081 int delay;
3082 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003083 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003084 // setup a new hold to debounce this
Wink Saville3e866722013-01-31 00:30:13 +00003085 if (mDefaultInetCondition > 50) {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003086 delay = Settings.Global.getInt(mContext.getContentResolver(),
3087 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003088 } else {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003089 delay = Settings.Global.getInt(mContext.getContentResolver(),
3090 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003091 }
3092 mInetConditionChangeInFlight = true;
3093 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville3e866722013-01-31 00:30:13 +00003094 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003095 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003096 // we've set the new condition, when this hold ends that will get picked up
3097 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003098 }
3099 }
3100
Wink Saville3e866722013-01-31 00:30:13 +00003101 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003102 if (DBG) {
Wink Saville3e866722013-01-31 00:30:13 +00003103 log("handleInetConditionHoldEnd: net=" + netType +
3104 ", condition=" + mDefaultInetCondition +
3105 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003106 }
3107 mInetConditionChangeInFlight = false;
3108
3109 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003110 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003111 return;
3112 }
3113 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003114 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003115 return;
3116 }
Wink Saville3e866722013-01-31 00:30:13 +00003117 // TODO: Figure out why this optimization sometimes causes a
3118 // change in mDefaultInetCondition to be missed and the
3119 // UI to not be updated.
3120 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3121 // if (DBG) log("no change in condition - aborting");
3122 // return;
3123 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003124 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3125 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003126 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003127 return;
3128 }
Wink Saville3e866722013-01-31 00:30:13 +00003129 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003130 sendInetConditionBroadcast(networkInfo);
3131 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003132 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003133
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003134 public ProxyProperties getProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003135 // this information is already available as a world read/writable jvm property
3136 // so this API change wouldn't have a benifit. It also breaks the passing
3137 // of proxy info to all the JVMs.
3138 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003139 synchronized (mProxyLock) {
3140 if (mGlobalProxy != null) return mGlobalProxy;
3141 return (mDefaultProxyDisabled ? null : mDefaultProxy);
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003142 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003143 }
3144
3145 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003146 enforceConnectivityInternalPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003147 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003148 if (proxyProperties == mGlobalProxy) return;
3149 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3150 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3151
3152 String host = "";
3153 int port = 0;
3154 String exclList = "";
3155 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3156 mGlobalProxy = new ProxyProperties(proxyProperties);
3157 host = mGlobalProxy.getHost();
3158 port = mGlobalProxy.getPort();
3159 exclList = mGlobalProxy.getExclusionList();
3160 } else {
3161 mGlobalProxy = null;
3162 }
3163 ContentResolver res = mContext.getContentResolver();
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003164 final long token = Binder.clearCallingIdentity();
3165 try {
3166 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3167 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3168 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3169 exclList);
3170 } finally {
3171 Binder.restoreCallingIdentity(token);
3172 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003173 }
3174
3175 if (mGlobalProxy == null) {
3176 proxyProperties = mDefaultProxy;
3177 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003178 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003179 }
3180
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003181 private void loadGlobalProxy() {
3182 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003183 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3184 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3185 String exclList = Settings.Global.getString(res,
3186 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003187 if (!TextUtils.isEmpty(host)) {
3188 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003189 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003190 mGlobalProxy = proxyProperties;
3191 }
3192 }
3193 }
3194
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003195 public ProxyProperties getGlobalProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003196 // this information is already available as a world read/writable jvm property
3197 // so this API change wouldn't have a benifit. It also breaks the passing
3198 // of proxy info to all the JVMs.
3199 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003200 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003201 return mGlobalProxy;
3202 }
3203 }
3204
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003205 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3206 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3207 proxy = null;
3208 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003209 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003210 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003211 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003212 mDefaultProxy = proxy;
3213
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003214 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003215 if (!mDefaultProxyDisabled) {
3216 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003217 }
3218 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003219 }
3220
3221 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003222 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3223 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003224 if (!TextUtils.isEmpty(proxy)) {
3225 String data[] = proxy.split(":");
Andreas Huber9df89552013-05-28 15:17:37 -07003226 if (data.length == 0) {
3227 return;
3228 }
3229
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003230 String proxyHost = data[0];
3231 int proxyPort = 8080;
3232 if (data.length > 1) {
3233 try {
3234 proxyPort = Integer.parseInt(data[1]);
3235 } catch (NumberFormatException e) {
3236 return;
3237 }
3238 }
3239 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3240 setGlobalProxy(p);
Andreas Huber9df89552013-05-28 15:17:37 -07003241 } else {
3242 setGlobalProxy(null);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003243 }
3244 }
3245
3246 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003247 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07003248 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003249 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003250 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3251 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003252 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07003253 final long ident = Binder.clearCallingIdentity();
3254 try {
3255 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3256 } finally {
3257 Binder.restoreCallingIdentity(ident);
3258 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003259 }
3260
3261 private static class SettingsObserver extends ContentObserver {
3262 private int mWhat;
3263 private Handler mHandler;
3264 SettingsObserver(Handler handler, int what) {
3265 super(handler);
3266 mHandler = handler;
3267 mWhat = what;
3268 }
3269
3270 void observe(Context context) {
3271 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003272 resolver.registerContentObserver(Settings.Global.getUriFor(
3273 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003274 }
3275
3276 @Override
3277 public void onChange(boolean selfChange) {
3278 mHandler.obtainMessage(mWhat).sendToTarget();
3279 }
3280 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003281
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003282 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003283 Slog.d(TAG, s);
3284 }
3285
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003286 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003287 Slog.e(TAG, s);
3288 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003289
repo syncf5de5572011-07-29 23:55:49 -07003290 int convertFeatureToNetworkType(int networkType, String feature) {
3291 int usedNetworkType = networkType;
3292
3293 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3294 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3295 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3296 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3297 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3298 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3299 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3300 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3301 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3302 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3303 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3304 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3305 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3306 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3307 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3308 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3309 } else {
3310 Slog.e(TAG, "Can't match any mobile netTracker!");
3311 }
3312 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3313 if (TextUtils.equals(feature, "p2p")) {
3314 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3315 } else {
3316 Slog.e(TAG, "Can't match any wifi netTracker!");
3317 }
3318 } else {
3319 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003320 }
repo syncf5de5572011-07-29 23:55:49 -07003321 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003322 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003323
3324 private static <T> T checkNotNull(T value, String message) {
3325 if (value == null) {
3326 throw new NullPointerException(message);
3327 }
3328 return value;
3329 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003330
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003331 /**
3332 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003333 * VpnBuilder and not available in ConnectivityManager. Permissions
3334 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003335 * @hide
3336 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003337 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003338 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003339 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003340 try {
3341 int type = mActiveDefaultNetwork;
Chad Brubakerccae0d32013-06-14 11:16:51 -07003342 int user = UserHandle.getUserId(Binder.getCallingUid());
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003343 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chad Brubakerccae0d32013-06-14 11:16:51 -07003344 synchronized(mVpns) {
3345 mVpns.get(user).protect(socket,
3346 mNetTrackers[type].getLinkProperties().getInterfaceName());
3347 }
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003348 return true;
3349 }
3350 } catch (Exception e) {
3351 // ignore
3352 } finally {
3353 try {
3354 socket.close();
3355 } catch (Exception e) {
3356 // ignore
3357 }
3358 }
3359 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003360 }
3361
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003362 /**
3363 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003364 * and not available in ConnectivityManager. Permissions are checked
3365 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003366 * @hide
3367 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003368 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003369 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003370 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003371 int user = UserHandle.getUserId(Binder.getCallingUid());
3372 synchronized(mVpns) {
3373 return mVpns.get(user).prepare(oldPackage, newPackage);
3374 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003375 }
3376
Chad Brubaker31de0b62013-07-11 13:29:30 -07003377 @Override
3378 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3379 enforceMarkNetworkSocketPermission();
3380 final long token = Binder.clearCallingIdentity();
3381 try {
3382 int mark = mNetd.getMarkForUid(uid);
3383 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3384 if (mark == -1) {
3385 mark = 0;
3386 }
3387 NetworkUtils.markSocket(socket.getFd(), mark);
3388 } catch (RemoteException e) {
3389 } finally {
3390 Binder.restoreCallingIdentity(token);
3391 }
3392 }
3393
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003394 /**
3395 * Configure a TUN interface and return its file descriptor. Parameters
3396 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003397 * and not available in ConnectivityManager. Permissions are checked in
3398 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003399 * @hide
3400 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003401 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003402 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003403 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003404 int user = UserHandle.getUserId(Binder.getCallingUid());
3405 synchronized(mVpns) {
3406 return mVpns.get(user).establish(config);
3407 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003408 }
3409
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003410 /**
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003411 * Start legacy VPN, controlling native daemons as needed. Creates a
3412 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003413 */
3414 @Override
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003415 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003416 throwIfLockdownEnabled();
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003417 final LinkProperties egress = getActiveLinkProperties();
3418 if (egress == null) {
3419 throw new IllegalStateException("Missing active network connection");
3420 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07003421 int user = UserHandle.getUserId(Binder.getCallingUid());
3422 synchronized(mVpns) {
3423 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3424 }
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003425 }
3426
3427 /**
3428 * Return the information of the ongoing legacy VPN. This method is used
3429 * by VpnSettings and not available in ConnectivityManager. Permissions
3430 * are checked in Vpn class.
3431 * @hide
3432 */
3433 @Override
3434 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003435 throwIfLockdownEnabled();
Chad Brubakerccae0d32013-06-14 11:16:51 -07003436 int user = UserHandle.getUserId(Binder.getCallingUid());
3437 synchronized(mVpns) {
3438 return mVpns.get(user).getLegacyVpnInfo();
3439 }
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003440 }
3441
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003442 /**
3443 * 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 Sharkey02e14d92012-08-04 15:24:58 -07003456 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003457 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003458 }
3459
Chad Brubakerccae0d32013-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 Brubakerccae0d32013-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 Greenwaltda77cb12013-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 Greenwaltda77cb12013-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 Greenwaltda77cb12013-04-05 17:14:19 -07003514 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003515 mDefaultProxyDisabled = false;
Robert Greenwaltda77cb12013-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 Brubakerccae0d32013-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 Sharkeyf2e722a2012-08-25 00:05:46 -07003583
3584 @Override
3585 public boolean updateLockdownVpn() {
Jeff Sharkeyc8a26872013-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 Sharkeyf2e722a2012-08-25 00:05:46 -07003590
3591 // Tear down existing lockdown if profile was removed
3592 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3593 if (mLockdownEnabled) {
Kenny Roote3a37b22013-02-14 10:18:38 -08003594 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyf2e722a2012-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 Brubakerccae0d32013-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 Sharkeyf2e722a2012-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 Sharkeyb103b252013-02-28 16:57:58 -08003629 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyf2e722a2012-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 Greenwalt030e1d32012-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 Greenwalt308b9ac2013-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 Saville690cb182013-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
Wink Savilleb56c4fd2013-07-19 09:27:56 -07003687 public int checkMobileProvisioning(final boolean sendNotification, int suggestedTimeOutMs,
Wink Saville690cb182013-06-29 21:10:57 -07003688 final ResultReceiver resultReceiver) {
3689 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3690 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3691 + " resultReceiver=" + resultReceiver);
3692 enforceChangePermission();
3693
Wink Saville9564f2b2013-07-16 17:16:37 -07003694 mFirstProvisioningCheckStarted = true;
3695
Wink Saville690cb182013-06-29 21:10:57 -07003696 int timeOutMs = suggestedTimeOutMs;
3697 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3698 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3699 }
3700
Wink Savillefdb84862013-07-02 10:55:14 -07003701 // Check that mobile networks are supported
3702 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3703 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3704 log("checkMobileProvisioning: X no mobile network");
3705 if (resultReceiver != null) {
3706 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3707 }
3708 return timeOutMs;
3709 }
3710
Wink Saville690cb182013-06-29 21:10:57 -07003711 final long token = Binder.clearCallingIdentity();
3712 try {
3713 CheckMp checkMp = new CheckMp(mContext, this);
3714 CheckMp.CallBack cb = new CheckMp.CallBack() {
3715 @Override
3716 void onComplete(Integer result) {
3717 log("CheckMp.onComplete: result=" + result);
3718 if (resultReceiver != null) {
3719 log("CheckMp.onComplete: send result");
3720 resultReceiver.send(result, null);
3721 }
Wink Savilleb56c4fd2013-07-19 09:27:56 -07003722 if (!sendNotification) {
3723 log("CheckMp.onComplete: done, not sending notification");
3724 return;
3725 }
Wink Saville690cb182013-06-29 21:10:57 -07003726 NetworkInfo ni =
3727 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3728 switch(result) {
3729 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3730 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3731 log("CheckMp.onComplete: ignore, connected or no connection");
3732 break;
3733 }
3734 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3735 log("CheckMp.onComplete: warm sim");
3736 String url = getProvisioningUrl();
3737 if (TextUtils.isEmpty(url)) {
3738 url = mContext.getResources()
3739 .getString(R.string.mobile_redirected_provisioning_url);
3740 }
3741 if (TextUtils.isEmpty(url) == false) {
3742 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3743 setNotificationVisible(true, ni, url);
3744 } else {
3745 log("CheckMp.onComplete: warm sim (redirected), no url");
3746 }
3747 break;
3748 }
3749 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3750 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
3751 String url = getProvisioningUrl();
3752 if (TextUtils.isEmpty(url) == false) {
3753 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3754 setNotificationVisible(true, ni, url);
3755 } else {
3756 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3757 }
3758 break;
3759 }
3760 default: {
3761 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3762 break;
3763 }
3764 }
3765 }
3766 };
3767 CheckMp.Params params =
3768 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3769 log("checkMobileProvisioning: params=" + params);
3770 setNotificationVisible(false, null, null);
3771 checkMp.execute(params);
3772 } finally {
3773 Binder.restoreCallingIdentity(token);
3774 log("checkMobileProvisioning: X");
3775 }
3776 return timeOutMs;
3777 }
3778
3779 static class CheckMp extends
3780 AsyncTask<CheckMp.Params, Void, Integer> {
3781 private static final String CHECKMP_TAG = "CheckMp";
3782 public static final int MAX_TIMEOUT_MS = 60000;
3783 private static final int SOCKET_TIMEOUT_MS = 5000;
3784 private Context mContext;
3785 private ConnectivityService mCs;
3786 private TelephonyManager mTm;
3787 private Params mParams;
3788
3789 /**
3790 * Parameters for AsyncTask.execute
3791 */
3792 static class Params {
3793 private String mUrl;
3794 private long mTimeOutMs;
3795 private CallBack mCb;
3796
3797 Params(String url, long timeOutMs, CallBack cb) {
3798 mUrl = url;
3799 mTimeOutMs = timeOutMs;
3800 mCb = cb;
3801 }
3802
3803 @Override
3804 public String toString() {
3805 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3806 }
3807 }
3808
3809 /**
3810 * The call back object passed in Params. onComplete will be called
3811 * on the main thread.
3812 */
3813 abstract static class CallBack {
3814 // Called on the main thread.
3815 abstract void onComplete(Integer result);
3816 }
3817
3818 public CheckMp(Context context, ConnectivityService cs) {
3819 mContext = context;
3820 mCs = cs;
3821
3822 // Setup access to TelephonyService we'll be using.
3823 mTm = (TelephonyManager) mContext.getSystemService(
3824 Context.TELEPHONY_SERVICE);
3825 }
3826
3827 /**
3828 * Get the default url to use for the test.
3829 */
3830 public String getDefaultUrl() {
3831 // See http://go/clientsdns for usage approval
3832 String server = Settings.Global.getString(mContext.getContentResolver(),
3833 Settings.Global.CAPTIVE_PORTAL_SERVER);
3834 if (server == null) {
3835 server = "clients3.google.com";
3836 }
3837 return "http://" + server + "/generate_204";
3838 }
3839
3840 /**
3841 * Detect if its possible to connect to the http url. DNS based detection techniques
3842 * do not work at all hotspots. The best way to check is to perform a request to
3843 * a known address that fetches the data we expect.
3844 */
3845 private synchronized Integer isMobileOk(Params params) {
3846 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3847 Uri orgUri = Uri.parse(params.mUrl);
3848 Random rand = new Random();
3849 mParams = params;
3850
3851 try {
3852 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3853 log("isMobileOk: not mobile capable");
3854 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3855 return result;
3856 }
3857
3858 // Enable fail fast as we'll do retries here and use a
3859 // hipri connection so the default connection stays active.
3860 log("isMobileOk: start hipri url=" + params.mUrl);
3861 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3862 mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3863 Phone.FEATURE_ENABLE_HIPRI, new Binder());
3864
3865 // Continue trying to connect until time has run out
3866 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3867 while(SystemClock.elapsedRealtime() < endTime) {
3868 try {
3869 // Wait for hipri to connect.
3870 // TODO: Don't poll and handle situation where hipri fails
3871 // because default is retrying. See b/9569540
3872 NetworkInfo.State state = mCs
3873 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3874 if (state != NetworkInfo.State.CONNECTED) {
3875 log("isMobileOk: not connected ni=" +
3876 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3877 sleep(1);
3878 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3879 continue;
3880 }
3881
3882 // Get of the addresses associated with the url host. We need to use the
3883 // address otherwise HttpURLConnection object will use the name to get
3884 // the addresses and is will try every address but that will bypass the
3885 // route to host we setup and the connection could succeed as the default
3886 // interface might be connected to the internet via wifi or other interface.
3887 InetAddress[] addresses;
3888 try {
3889 addresses = InetAddress.getAllByName(orgUri.getHost());
3890 } catch (UnknownHostException e) {
3891 log("isMobileOk: UnknownHostException");
3892 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3893 return result;
3894 }
3895 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3896
3897 // Get the type of addresses supported by this link
3898 LinkProperties lp = mCs.getLinkProperties(
3899 ConnectivityManager.TYPE_MOBILE_HIPRI);
3900 boolean linkHasIpv4 = hasIPv4Address(lp);
3901 boolean linkHasIpv6 = hasIPv6Address(lp);
3902 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3903 + " linkHasIpv6=" + linkHasIpv6);
3904
3905 // Loop through at most 3 valid addresses or all of the address or until
3906 // we run out of time
3907 int loops = Math.min(3, addresses.length);
3908 for(int validAddr=0, addrTried=0;
3909 (validAddr < loops) && (addrTried < addresses.length)
3910 && (SystemClock.elapsedRealtime() < endTime);
3911 addrTried ++) {
3912
3913 // Choose the address at random but make sure its type is supported
3914 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3915 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3916 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3917 // Valid address, so use it
3918 validAddr += 1;
3919 } else {
3920 // Invalid address so try next address
3921 continue;
3922 }
3923
3924 // Make a route to host so we check the specific interface.
3925 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3926 hostAddr.getAddress())) {
3927 // Wait a short time to be sure the route is established ??
3928 log("isMobileOk:"
3929 + " wait to establish route to hostAddr=" + hostAddr);
3930 sleep(3);
3931 } else {
3932 log("isMobileOk:"
3933 + " could not establish route to hostAddr=" + hostAddr);
3934 continue;
3935 }
3936
3937 // Rewrite the url to have numeric address to use the specific route.
3938 // I also set the "Connection" to "Close" as by default "Keep-Alive"
3939 // is used which is useless in this case.
3940 URL newUrl = new URL(orgUri.getScheme() + "://"
3941 + hostAddr.getHostAddress() + orgUri.getPath());
3942 log("isMobileOk: newUrl=" + newUrl);
3943
3944 HttpURLConnection urlConn = null;
3945 try {
3946 // Open the connection set the request header and get the response
3947 urlConn = (HttpURLConnection) newUrl.openConnection(
3948 java.net.Proxy.NO_PROXY);
3949 urlConn.setInstanceFollowRedirects(false);
3950 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3951 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3952 urlConn.setUseCaches(false);
3953 urlConn.setAllowUserInteraction(false);
3954 urlConn.setRequestProperty("Connection", "close");
3955 int responseCode = urlConn.getResponseCode();
3956 if (responseCode == 204) {
3957 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
3958 } else {
3959 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3960 }
3961 log("isMobileOk: connected responseCode=" + responseCode);
3962 urlConn.disconnect();
3963 urlConn = null;
3964 return result;
3965 } catch (Exception e) {
3966 log("isMobileOk: HttpURLConnection Exception e=" + e);
3967 if (urlConn != null) {
3968 urlConn.disconnect();
3969 urlConn = null;
3970 }
3971 }
3972 }
3973 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3974 log("isMobileOk: loops|timed out");
3975 return result;
3976 } catch (Exception e) {
3977 log("isMobileOk: Exception e=" + e);
3978 continue;
3979 }
3980 }
3981 log("isMobileOk: timed out");
3982 } finally {
3983 log("isMobileOk: F stop hipri");
3984 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3985 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3986 Phone.FEATURE_ENABLE_HIPRI);
3987 log("isMobileOk: X result=" + result);
3988 }
3989 return result;
3990 }
3991
3992 @Override
3993 protected Integer doInBackground(Params... params) {
3994 return isMobileOk(params[0]);
3995 }
3996
3997 @Override
3998 protected void onPostExecute(Integer result) {
3999 log("onPostExecute: result=" + result);
4000 if ((mParams != null) && (mParams.mCb != null)) {
4001 mParams.mCb.onComplete(result);
4002 }
4003 }
4004
4005 private String inetAddressesToString(InetAddress[] addresses) {
4006 StringBuffer sb = new StringBuffer();
4007 boolean firstTime = true;
4008 for(InetAddress addr : addresses) {
4009 if (firstTime) {
4010 firstTime = false;
4011 } else {
4012 sb.append(",");
4013 }
4014 sb.append(addr);
4015 }
4016 return sb.toString();
4017 }
4018
4019 private void printNetworkInfo() {
4020 boolean hasIccCard = mTm.hasIccCard();
4021 int simState = mTm.getSimState();
4022 log("hasIccCard=" + hasIccCard
4023 + " simState=" + simState);
4024 NetworkInfo[] ni = mCs.getAllNetworkInfo();
4025 if (ni != null) {
4026 log("ni.length=" + ni.length);
4027 for (NetworkInfo netInfo: ni) {
4028 log("netInfo=" + netInfo.toString());
4029 }
4030 } else {
4031 log("no network info ni=null");
4032 }
4033 }
4034
4035 /**
4036 * Sleep for a few seconds then return.
4037 * @param seconds
4038 */
4039 private static void sleep(int seconds) {
4040 try {
4041 Thread.sleep(seconds * 1000);
4042 } catch (InterruptedException e) {
4043 e.printStackTrace();
4044 }
4045 }
4046
4047 public boolean hasIPv4Address(LinkProperties lp) {
4048 return lp.hasIPv4Address();
4049 }
4050
4051 // Not implemented in LinkProperties, do it here.
4052 public boolean hasIPv6Address(LinkProperties lp) {
4053 for (LinkAddress address : lp.getLinkAddresses()) {
4054 if (address.getAddress() instanceof Inet6Address) {
4055 return true;
4056 }
4057 }
4058 return false;
4059 }
4060
4061 private void log(String s) {
4062 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4063 }
4064 }
4065
4066 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4067
4068 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
4069 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
4070
4071 Resources r = Resources.getSystem();
4072 NotificationManager notificationManager = (NotificationManager) mContext
4073 .getSystemService(Context.NOTIFICATION_SERVICE);
4074
4075 if (visible) {
4076 CharSequence title;
4077 CharSequence details;
4078 int icon;
4079 switch (networkInfo.getType()) {
4080 case ConnectivityManager.TYPE_WIFI:
4081 log("setNotificationVisible: TYPE_WIFI");
4082 title = r.getString(R.string.wifi_available_sign_in, 0);
4083 details = r.getString(R.string.network_available_sign_in_detailed,
4084 networkInfo.getExtraInfo());
4085 icon = R.drawable.stat_notify_wifi_in_range;
4086 break;
4087 case ConnectivityManager.TYPE_MOBILE:
4088 case ConnectivityManager.TYPE_MOBILE_HIPRI:
4089 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
4090 title = r.getString(R.string.network_available_sign_in, 0);
4091 // TODO: Change this to pull from NetworkInfo once a printable
4092 // name has been added to it
4093 details = mTelephonyManager.getNetworkOperatorName();
4094 icon = R.drawable.stat_notify_rssi_in_range;
4095 break;
4096 default:
4097 log("setNotificationVisible: other type=" + networkInfo.getType());
4098 title = r.getString(R.string.network_available_sign_in, 0);
4099 details = r.getString(R.string.network_available_sign_in_detailed,
4100 networkInfo.getExtraInfo());
4101 icon = R.drawable.stat_notify_rssi_in_range;
4102 break;
4103 }
4104
4105 Notification notification = new Notification();
4106 notification.when = 0;
4107 notification.icon = icon;
4108 notification.flags = Notification.FLAG_AUTO_CANCEL;
4109 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4110 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4111 Intent.FLAG_ACTIVITY_NEW_TASK);
4112 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4113 notification.tickerText = title;
4114 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4115
4116 log("setNotificaitionVisible: notify notificaiton=" + notification);
4117 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4118 } else {
4119 log("setNotificaitionVisible: cancel");
4120 notificationManager.cancel(NOTIFICATION_ID, 1);
4121 }
4122 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
4123 }
4124
4125 private String getProvisioningUrl() {
4126 String url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Savilledfabd992013-07-10 23:00:07 -07004127 log("getProvisioningUrl: mobile_provisioning_url=" + url);
Wink Saville690cb182013-06-29 21:10:57 -07004128
Wink Savilledfabd992013-07-10 23:00:07 -07004129 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville690cb182013-06-29 21:10:57 -07004130 if (!TextUtils.isEmpty(url)) {
Wink Savilledfabd992013-07-10 23:00:07 -07004131 String phoneNumber = mTelephonyManager.getLine1Number();
4132 if (TextUtils.isEmpty(phoneNumber)) {
4133 phoneNumber = "0000000000";
4134 }
Wink Saville690cb182013-06-29 21:10:57 -07004135 url = String.format(url,
4136 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4137 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savilledfabd992013-07-10 23:00:07 -07004138 phoneNumber /* Phone numer */);
Wink Saville690cb182013-06-29 21:10:57 -07004139 }
4140
Wink Saville690cb182013-06-29 21:10:57 -07004141 return url;
4142 }
Chad Brubakerccae0d32013-06-14 11:16:51 -07004143
4144 private void onUserStart(int userId) {
4145 synchronized(mVpns) {
4146 Vpn userVpn = mVpns.get(userId);
4147 if (userVpn != null) {
4148 loge("Starting user already has a VPN");
4149 return;
4150 }
4151 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
4152 mVpns.put(userId, userVpn);
4153 userVpn.startMonitoring(mContext, mTrackerHandler);
4154 }
4155 }
4156
4157 private void onUserStop(int userId) {
4158 synchronized(mVpns) {
4159 Vpn userVpn = mVpns.get(userId);
4160 if (userVpn == null) {
4161 loge("Stopping user has no VPN");
4162 return;
4163 }
4164 mVpns.delete(userId);
4165 }
4166 }
4167
4168 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4169 @Override
4170 public void onReceive(Context context, Intent intent) {
4171 final String action = intent.getAction();
4172 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4173 if (userId == UserHandle.USER_NULL) return;
4174
4175 if (Intent.ACTION_USER_STARTING.equals(action)) {
4176 onUserStart(userId);
4177 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
4178 onUserStop(userId);
4179 }
4180 }
4181 };
The Android Open Source Project28527d22009-03-03 19:31:44 -08004182}