blob: 3a338a9847920db01605b07fd303ed29dcba9fbc [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 Sharkeyebcc7972012-08-25 00:05:46 -070019import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey4434b0b2011-06-16 13:04:20 -070020import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baib5da5752012-06-20 14:29:57 -070021import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070022import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
23import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
25import static android.net.ConnectivityManager.TYPE_DUMMY;
26import static android.net.ConnectivityManager.TYPE_ETHERNET;
27import static android.net.ConnectivityManager.TYPE_MOBILE;
28import static android.net.ConnectivityManager.TYPE_WIFI;
29import static android.net.ConnectivityManager.TYPE_WIMAX;
30import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070031import static android.net.ConnectivityManager.isNetworkTypeValid;
32import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070034
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080035import android.bluetooth.BluetoothTetheringDataTracker;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070036import android.content.BroadcastReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080037import android.content.ContentResolver;
38import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090039import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080040import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070041import android.content.IntentFilter;
The Android Open Source Project28527d22009-03-03 19:31:44 -080042import android.content.pm.PackageManager;
tk.mun093f55c2011-10-13 22:51:57 +090043import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070044import android.database.ContentObserver;
Irfan Sheriff0ad0d132012-08-16 12:49:23 -070045import android.net.CaptivePortalTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080046import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080047import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080048import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080049import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070050import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070051import android.net.INetworkPolicyListener;
52import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070053import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070054import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080055import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070056import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080057import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070058import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080059import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070060import android.net.NetworkInfo.DetailedState;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070061import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070062import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070064import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070065import android.net.Proxy;
66import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070067import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080068import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090069import android.net.wimax.WimaxManagerConstants;
The Android Open Source Project28527d22009-03-03 19:31:44 -080070import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040071import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080072import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070073import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070074import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070075import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080076import android.os.Looper;
77import android.os.Message;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070078import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070079import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -070080import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070081import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080082import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070083import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080084import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -070085import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080086import android.provider.Settings;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070087import android.security.Credentials;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -070088import android.security.KeyStore;
Robert Greenwalt2034b912009-08-12 16:08:25 -070089import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080090import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080091import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070092import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080093
Chia-chi Yehbded3eb2011-07-04 03:23:12 -070094import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -070095import com.android.internal.net.VpnConfig;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -070096import com.android.internal.net.VpnProfile;
Robert Greenwalt2034b912009-08-12 16:08:25 -070097import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -070098import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -070099import com.android.server.am.BatteryStatsService;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800100import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700101import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700102import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700103import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700104import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700105import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700106
tk.mun093f55c2011-10-13 22:51:57 +0900107import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700108
The Android Open Source Project28527d22009-03-03 19:31:44 -0800109import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700110import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800111import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900112import java.lang.reflect.Constructor;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700113import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700114import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700115import java.net.InetAddress;
116import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700117import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700118import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700119import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700120import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700121import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700122import java.util.List;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800123
124/**
125 * @hide
126 */
127public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700128 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800129
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700130 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700131 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800132
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700133 private static final boolean LOGD_RULES = false;
134
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700135 // TODO: create better separation between radio types and network types
136
Robert Greenwalt2034b912009-08-12 16:08:25 -0700137 // how long to wait before switching back to a radio's default network
138 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
139 // system property that can override the above value
140 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
141 "android.telephony.apn-restore";
142
Robert Greenwaltbd492212011-05-06 17:10:53 -0700143 // used in recursive route setting to add gateways for the host for which
144 // a host route was requested.
145 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
146
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800147 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800148 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800149
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700150 private KeyStore mKeyStore;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700151
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700152 private Vpn mVpn;
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700153 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700154
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700155 private boolean mLockdownEnabled;
156 private LockdownVpnTracker mLockdownTracker;
157
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700158 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
159 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700160 /** Currently active network rules by UID. */
161 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700162 /** Set of ifaces that are costly. */
163 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700164
The Android Open Source Project28527d22009-03-03 19:31:44 -0800165 /**
166 * Sometimes we want to refer to the individual network state
167 * trackers separately, and sometimes we just want to treat them
168 * abstractly.
169 */
170 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700171
Irfan Sheriff0ad0d132012-08-16 12:49:23 -0700172 /* Handles captive portal check on a network */
173 private CaptivePortalTracker mCaptivePortalTracker;
174
Robert Greenwalt2034b912009-08-12 16:08:25 -0700175 /**
Wink Saville051a6642011-07-13 13:44:13 -0700176 * The link properties that define the current links
177 */
178 private LinkProperties mCurrentLinkProperties[];
179
180 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700181 * A per Net list of the PID's that requested access to the net
182 * used both as a refcount and for per-PID DNS selection
183 */
184 private List mNetRequestersPids[];
185
Robert Greenwalt2034b912009-08-12 16:08:25 -0700186 // priority order of the nettrackers
187 // (excluding dynamically set mNetworkPreference)
188 // TODO - move mNetworkTypePreference into this
189 private int[] mPriorityList;
190
The Android Open Source Project28527d22009-03-03 19:31:44 -0800191 private Context mContext;
192 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700193 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700194 // 0 is full bad, 100 is full good
195 private int mDefaultInetCondition = 0;
196 private int mDefaultInetConditionPublished = 0;
197 private boolean mInetConditionChangeInFlight = false;
198 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800199
Chia-chi Yehcc844502011-07-14 18:01:57 -0700200 private Object mDnsLock = new Object();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800201 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700202 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800203
204 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700205 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800206
Robert Greenwalt355205c2011-05-10 15:05:02 -0700207 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700208 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700209
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700210 private static final int ENABLED = 1;
211 private static final int DISABLED = 0;
212
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700213 private static final boolean ADD = true;
214 private static final boolean REMOVE = false;
215
216 private static final boolean TO_DEFAULT_TABLE = true;
217 private static final boolean TO_SECONDARY_TABLE = false;
218
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700219 /**
220 * used internally as a delayed event to make us switch back to the
221 * default network
222 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700223 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700224
225 /**
226 * used internally to change our mobile data enabled flag
227 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700228 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700229
230 /**
231 * used internally to change our network preference setting
232 * arg1 = networkType to prefer
233 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700234 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700235
236 /**
237 * used internally to synchronize inet condition reports
238 * arg1 = networkType
239 * arg2 = condition (0 bad, 100 good)
240 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700241 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700242
243 /**
244 * used internally to mark the end of inet condition hold periods
245 * arg1 = networkType
246 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700247 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700248
249 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700250 * used internally to set enable/disable cellular data
251 * arg1 = ENBALED or DISABLED
252 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700253 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700254
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700255 /**
256 * used internally to clear a wakelock when transitioning
257 * from one net to another
258 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700259 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700260
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700261 /**
262 * used internally to reload global proxy settings
263 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700264 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700265
Robert Greenwalt34848c02011-03-25 13:09:25 -0700266 /**
267 * used internally to set external dependency met/unmet
268 * arg1 = ENABLED (met) or DISABLED (unmet)
269 * arg2 = NetworkType
270 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700271 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700272
Chia-chi Yehcc844502011-07-14 18:01:57 -0700273 /**
274 * used internally to restore DNS properties back to the
275 * default network
276 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700277 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700278
Wink Saville7e4333c2011-08-05 11:40:22 -0700279 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700280 * used internally to send a sticky broadcast delayed.
281 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700282 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700283
Jeff Sharkey805662d2011-08-19 02:24:24 -0700284 /**
285 * Used internally to
286 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
287 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700288 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700289
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700290 private static final int EVENT_VPN_STATE_CHANGED = 14;
291
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700292 /** Handler used for internal events. */
293 private InternalHandler mHandler;
294 /** Handler used for incoming {@link NetworkStateTracker} events. */
295 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700296
297 // list of DeathRecipients used to make sure features are turned off when
298 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500299 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700300
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400301 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800302 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400303
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700304 private PowerManager.WakeLock mNetTransitionWakeLock;
305 private String mNetTransitionWakeLockCausedBy = "";
306 private int mNetTransitionWakeLockSerialNumber;
307 private int mNetTransitionWakeLockTimeout;
308
Robert Greenwalt94daa182010-09-01 11:34:05 -0700309 private InetAddress mDefaultDns;
310
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700311 // this collection is used to refcount the added routes - if there are none left
312 // it's time to remove the route from the route table
313 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
314
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700315 // used in DBG mode to track inet condition reports
316 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
317 private ArrayList mInetLog;
318
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700319 // track the current default http proxy - tell the world if we get a new one (real change)
320 private ProxyProperties mDefaultProxy = null;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700321 private Object mDefaultProxyLock = new Object();
322 private boolean mDefaultProxyDisabled = false;
323
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700324 // track the global proxy.
325 private ProxyProperties mGlobalProxy = null;
326 private final Object mGlobalProxyLock = new Object();
327
328 private SettingsObserver mSettingsObserver;
329
Robert Greenwalt34848c02011-03-25 13:09:25 -0700330 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700331 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700332
Robert Greenwalt12c44552009-12-07 11:33:18 -0800333 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700334 public int mSimultaneity;
335 public int mType;
336 public RadioAttributes(String init) {
337 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700338 mType = Integer.parseInt(fragments[0]);
339 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700340 }
341 }
342 RadioAttributes[] mRadioAttributes;
343
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700344 // the set of network types that can only be enabled by system/sig apps
345 List mProtectedNetworks;
346
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700347 public ConnectivityService(Context context, INetworkManagementService netd,
348 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700349 // Currently, omitting a NetworkFactory will create one internally
350 // TODO: create here when we have cleaner WiMAX support
351 this(context, netd, statsService, policyManager, null);
352 }
353
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700354 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700355 INetworkStatsService statsService, INetworkPolicyManager policyManager,
356 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800357 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800358
Wink Saville775aad62010-09-02 19:23:52 -0700359 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
360 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700361 mHandler = new InternalHandler(handlerThread.getLooper());
362 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700363
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700364 if (netFactory == null) {
365 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
366 }
367
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800368 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800369 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
370 String id = Settings.Secure.getString(context.getContentResolver(),
371 Settings.Secure.ANDROID_ID);
372 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700373 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800374 SystemProperties.set("net.hostname", name);
375 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800376 }
377
Robert Greenwalt94daa182010-09-01 11:34:05 -0700378 // read our default dns server ip
379 String dns = Settings.Secure.getString(context.getContentResolver(),
380 Settings.Secure.DEFAULT_DNS_SERVER);
381 if (dns == null || dns.length() == 0) {
382 dns = context.getResources().getString(
383 com.android.internal.R.string.config_default_dns_server);
384 }
385 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800386 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
387 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800388 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700389 }
390
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700391 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700392 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700393 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700394 mKeyStore = KeyStore.getInstance();
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700395
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700396 try {
397 mPolicyManager.registerListener(mPolicyListener);
398 } catch (RemoteException e) {
399 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700400 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700401 }
402
403 final PowerManager powerManager = (PowerManager) context.getSystemService(
404 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700405 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
406 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
407 com.android.internal.R.integer.config_networkTransitionTimeout);
408
Robert Greenwalt2034b912009-08-12 16:08:25 -0700409 mNetTrackers = new NetworkStateTracker[
410 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700411 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700412
The Android Open Source Project28527d22009-03-03 19:31:44 -0800413 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700414
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700415 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700416 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700417
Robert Greenwalt2034b912009-08-12 16:08:25 -0700418 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700419 String[] raStrings = context.getResources().getStringArray(
420 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700421 for (String raString : raStrings) {
422 RadioAttributes r = new RadioAttributes(raString);
423 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800424 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700425 continue;
426 }
427 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800428 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700429 r.mType);
430 continue;
431 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700432 mRadioAttributes[r.mType] = r;
433 }
434
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700435 String[] naStrings = context.getResources().getStringArray(
436 com.android.internal.R.array.networkAttributes);
437 for (String naString : naStrings) {
438 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700439 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700440 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800441 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700442 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700443 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700444 }
Wink Savillef2a62832011-04-07 14:23:45 -0700445 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800446 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700447 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700448 continue;
449 }
Wink Savillef2a62832011-04-07 14:23:45 -0700450 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800451 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700452 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700453 continue;
454 }
Wink Savillef2a62832011-04-07 14:23:45 -0700455 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700456 mNetworksDefined++;
457 } catch(Exception e) {
458 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700459 }
460 }
461
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700462 mProtectedNetworks = new ArrayList<Integer>();
463 int[] protectedNetworks = context.getResources().getIntArray(
464 com.android.internal.R.array.config_protectedNetworks);
465 for (int p : protectedNetworks) {
466 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
467 mProtectedNetworks.add(p);
468 } else {
469 if (DBG) loge("Ignoring protectedNetwork " + p);
470 }
471 }
472
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700473 // high priority first
474 mPriorityList = new int[mNetworksDefined];
475 {
476 int insertionPoint = mNetworksDefined-1;
477 int currentLowest = 0;
478 int nextLowest = 0;
479 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700480 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700481 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700482 if (na.priority < currentLowest) continue;
483 if (na.priority > currentLowest) {
484 if (na.priority < nextLowest || nextLowest == 0) {
485 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700486 }
487 continue;
488 }
Wink Savillef2a62832011-04-07 14:23:45 -0700489 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700490 }
491 currentLowest = nextLowest;
492 nextLowest = 0;
493 }
494 }
495
496 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
497 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700498 mNetRequestersPids[i] = new ArrayList();
499 }
500
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500501 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700502
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700503 mNumDnsEntries = 0;
504
505 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
506 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700507
508 // Create and start trackers for hard-coded networks
509 for (int targetNetworkType : mPriorityList) {
510 final NetworkConfig config = mNetConfigs[targetNetworkType];
511 final NetworkStateTracker tracker;
512 try {
513 tracker = netFactory.createTracker(targetNetworkType, config);
514 mNetTrackers[targetNetworkType] = tracker;
515 } catch (IllegalArgumentException e) {
516 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
517 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700518 continue;
519 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700520
521 tracker.startMonitoring(context, mTrackerHandler);
522 if (config.isDefault()) {
523 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800524 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700525 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800526
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700527 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700528 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700529 mTethering.getTetherableWifiRegexs().length != 0 ||
530 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700531 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800532
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700533 mVpn = new Vpn(mContext, mVpnCallback, mNetd);
534 mVpn.startMonitoring(mContext, mTrackerHandler);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700535
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700536 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700537 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700538 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700539 } catch (RemoteException e) {
540 loge("Error registering observer :" + e);
541 }
542
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700543 if (DBG) {
544 mInetLog = new ArrayList();
545 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700546
547 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
548 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800549
550 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800551 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700552
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700553 /**
554 * Factory that creates {@link NetworkStateTracker} instances using given
555 * {@link NetworkConfig}.
556 */
557 public interface NetworkFactory {
558 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
559 }
560
561 private static class DefaultNetworkFactory implements NetworkFactory {
562 private final Context mContext;
563 private final Handler mTrackerHandler;
564
565 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
566 mContext = context;
567 mTrackerHandler = trackerHandler;
568 }
569
570 @Override
571 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
572 switch (config.radio) {
573 case TYPE_WIFI:
574 return new WifiStateTracker(targetNetworkType, config.name);
575 case TYPE_MOBILE:
576 return new MobileDataStateTracker(targetNetworkType, config.name);
577 case TYPE_DUMMY:
578 return new DummyDataStateTracker(targetNetworkType, config.name);
579 case TYPE_BLUETOOTH:
580 return BluetoothTetheringDataTracker.getInstance();
581 case TYPE_WIMAX:
582 return makeWimaxStateTracker(mContext, mTrackerHandler);
583 case TYPE_ETHERNET:
584 return EthernetDataTracker.getInstance();
585 default:
586 throw new IllegalArgumentException(
587 "Trying to create a NetworkStateTracker for an unknown radio type: "
588 + config.radio);
589 }
590 }
591 }
592
593 /**
594 * Loads external WiMAX library and registers as system service, returning a
595 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
596 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
597 */
598 private static NetworkStateTracker makeWimaxStateTracker(
599 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700600 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900601 DexClassLoader wimaxClassLoader;
602 Class wimaxStateTrackerClass = null;
603 Class wimaxServiceClass = null;
604 Class wimaxManagerClass;
605 String wimaxJarLocation;
606 String wimaxLibLocation;
607 String wimaxManagerClassName;
608 String wimaxServiceClassName;
609 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800610
tk.mun093f55c2011-10-13 22:51:57 +0900611 NetworkStateTracker wimaxStateTracker = null;
612
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700613 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900614 com.android.internal.R.bool.config_wimaxEnabled);
615
616 if (isWimaxEnabled) {
617 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700618 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900619 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700620 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900621 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700622 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900623 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700624 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900625 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700626 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900627 com.android.internal.R.string.config_wimaxStateTrackerClassname);
628
629 log("wimaxJarLocation: " + wimaxJarLocation);
630 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700631 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900632 wimaxLibLocation, ClassLoader.getSystemClassLoader());
633
634 try {
635 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
636 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
637 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
638 } catch (ClassNotFoundException ex) {
639 loge("Exception finding Wimax classes: " + ex.toString());
640 return null;
641 }
642 } catch(Resources.NotFoundException ex) {
643 loge("Wimax Resources does not exist!!! ");
644 return null;
645 }
646
647 try {
648 log("Starting Wimax Service... ");
649
650 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
651 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700652 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
653 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900654
655 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
656 (new Class[] {Context.class, wimaxStateTrackerClass});
657 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700658 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900659 wmxSrvConst.setAccessible(false);
660
661 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
662
663 } catch(Exception ex) {
664 loge("Exception creating Wimax classes: " + ex.toString());
665 return null;
666 }
667 } else {
668 loge("Wimax is not enabled or not added to the network attributes!!! ");
669 return null;
670 }
671
672 return wimaxStateTracker;
673 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700674
The Android Open Source Project28527d22009-03-03 19:31:44 -0800675 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700676 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800677 * @param preference the new preference
678 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700679 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800680 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700681
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700682 mHandler.sendMessage(
683 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800684 }
685
686 public int getNetworkPreference() {
687 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700688 int preference;
689 synchronized(this) {
690 preference = mNetworkPreference;
691 }
692 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800693 }
694
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700695 private void handleSetNetworkPreference(int preference) {
696 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700697 mNetConfigs[preference] != null &&
698 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700699 if (mNetworkPreference != preference) {
700 final ContentResolver cr = mContext.getContentResolver();
701 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
702 synchronized(this) {
703 mNetworkPreference = preference;
704 }
705 enforcePreference();
706 }
707 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800708 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700709
Wink Saville4f0de1e2011-08-04 15:01:58 -0700710 private int getConnectivityChangeDelay() {
711 final ContentResolver cr = mContext.getContentResolver();
712
713 /** Check system properties for the default value then use secure settings value, if any. */
714 int defaultDelay = SystemProperties.getInt(
715 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
716 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
717 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
718 defaultDelay);
719 }
720
The Android Open Source Project28527d22009-03-03 19:31:44 -0800721 private int getPersistedNetworkPreference() {
722 final ContentResolver cr = mContext.getContentResolver();
723
724 final int networkPrefSetting = Settings.Secure
725 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
726 if (networkPrefSetting != -1) {
727 return networkPrefSetting;
728 }
729
730 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
731 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700732
The Android Open Source Project28527d22009-03-03 19:31:44 -0800733 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700734 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800735 * In this method, we only tear down a non-preferred network. Establishing
736 * a connection to the preferred network is taken care of when we handle
737 * the disconnect event from the non-preferred network
738 * (see {@link #handleDisconnect(NetworkInfo)}).
739 */
740 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700741 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800742 return;
743
Robert Greenwalt2034b912009-08-12 16:08:25 -0700744 if (!mNetTrackers[mNetworkPreference].isAvailable())
745 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800746
Robert Greenwalt2034b912009-08-12 16:08:25 -0700747 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700748 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700749 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700750 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800751 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700752 " in enforcePreference");
753 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700754 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800755 }
756 }
757 }
758
759 private boolean teardown(NetworkStateTracker netTracker) {
760 if (netTracker.teardown()) {
761 netTracker.setTeardownRequested(true);
762 return true;
763 } else {
764 return false;
765 }
766 }
767
768 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700769 * Check if UID should be blocked from using the network represented by the
770 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700771 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700772 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
773 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700774
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700775 final boolean networkCostly;
776 final int uidRules;
777 synchronized (mRulesLock) {
778 networkCostly = mMeteredIfaces.contains(iface);
779 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700780 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700781
782 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
783 return true;
784 }
785
786 // no restrictive rules; network is visible
787 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700788 }
789
790 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700791 * Return a filtered {@link NetworkInfo}, potentially marked
792 * {@link DetailedState#BLOCKED} based on
793 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700794 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700795 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
796 NetworkInfo info = tracker.getNetworkInfo();
797 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700798 // network is blocked; clone and override state
799 info = new NetworkInfo(info);
800 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700801 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700802 if (mLockdownTracker != null) {
803 info = mLockdownTracker.augmentNetworkInfo(info);
804 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700805 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700806 }
807
808 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800809 * Return NetworkInfo for the active (i.e., connected) network interface.
810 * It is assumed that at most one network is active at a time. If more
811 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700812 * @return the info for the active network, or {@code null} if none is
813 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800814 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700815 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800816 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700817 enforceAccessPermission();
818 final int uid = Binder.getCallingUid();
819 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800820 }
821
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700822 public NetworkInfo getActiveNetworkInfoUnfiltered() {
823 enforceAccessPermission();
824 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
825 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
826 if (tracker != null) {
827 return tracker.getNetworkInfo();
828 }
829 }
830 return null;
831 }
832
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700833 @Override
834 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
835 enforceConnectivityInternalPermission();
836 return getNetworkInfo(mActiveDefaultNetwork, uid);
837 }
838
839 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800840 public NetworkInfo getNetworkInfo(int networkType) {
841 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700842 final int uid = Binder.getCallingUid();
843 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800844 }
845
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700846 private NetworkInfo getNetworkInfo(int networkType, int uid) {
847 NetworkInfo info = null;
848 if (isNetworkTypeValid(networkType)) {
849 final NetworkStateTracker tracker = mNetTrackers[networkType];
850 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700851 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700852 }
853 }
854 return info;
855 }
856
857 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800858 public NetworkInfo[] getAllNetworkInfo() {
859 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700860 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700861 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700862 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700863 for (NetworkStateTracker tracker : mNetTrackers) {
864 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700865 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700866 }
867 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800868 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700869 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800870 }
871
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700872 @Override
873 public boolean isNetworkSupported(int networkType) {
874 enforceAccessPermission();
875 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
876 }
877
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700878 /**
879 * Return LinkProperties for the active (i.e., connected) default
880 * network interface. It is assumed that at most one default network
881 * is active at a time. If more than one is active, it is indeterminate
882 * which will be returned.
883 * @return the ip properties for the active network, or {@code null} if
884 * none is active
885 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700886 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700887 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700888 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700889 }
890
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700891 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700892 public LinkProperties getLinkProperties(int networkType) {
893 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700894 if (isNetworkTypeValid(networkType)) {
895 final NetworkStateTracker tracker = mNetTrackers[networkType];
896 if (tracker != null) {
897 return tracker.getLinkProperties();
898 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700899 }
900 return null;
901 }
902
Jeff Sharkey21062e72011-05-28 20:56:34 -0700903 @Override
904 public NetworkState[] getAllNetworkState() {
905 enforceAccessPermission();
906 final int uid = Binder.getCallingUid();
907 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700908 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700909 for (NetworkStateTracker tracker : mNetTrackers) {
910 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700911 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700912 result.add(new NetworkState(
913 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
914 }
915 }
916 }
917 return result.toArray(new NetworkState[result.size()]);
918 }
919
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700920 private NetworkState getNetworkStateUnchecked(int networkType) {
921 if (isNetworkTypeValid(networkType)) {
922 final NetworkStateTracker tracker = mNetTrackers[networkType];
923 if (tracker != null) {
924 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
925 tracker.getLinkCapabilities());
926 }
927 }
928 return null;
929 }
930
931 @Override
932 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
933 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700934
935 final long token = Binder.clearCallingIdentity();
936 try {
937 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
938 if (state != null) {
939 try {
940 return mPolicyManager.getNetworkQuotaInfo(state);
941 } catch (RemoteException e) {
942 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700943 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700944 return null;
945 } finally {
946 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700947 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700948 }
949
Jeff Sharkeyd00b1302012-04-12 18:34:54 -0700950 @Override
951 public boolean isActiveNetworkMetered() {
952 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700953 final long token = Binder.clearCallingIdentity();
954 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -0700955 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700956 } finally {
957 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -0700958 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -0700959 }
960
Jeff Sharkeyedf85d42012-04-30 15:47:05 -0700961 private boolean isNetworkMeteredUnchecked(int networkType) {
962 final NetworkState state = getNetworkStateUnchecked(networkType);
963 if (state != null) {
964 try {
965 return mPolicyManager.isNetworkMetered(state);
966 } catch (RemoteException e) {
967 }
968 }
969 return false;
970 }
971
The Android Open Source Project28527d22009-03-03 19:31:44 -0800972 public boolean setRadios(boolean turnOn) {
973 boolean result = true;
974 enforceChangePermission();
975 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700976 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800977 }
978 return result;
979 }
980
981 public boolean setRadio(int netType, boolean turnOn) {
982 enforceChangePermission();
983 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
984 return false;
985 }
986 NetworkStateTracker tracker = mNetTrackers[netType];
987 return tracker != null && tracker.setRadio(turnOn);
988 }
989
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700990 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
991 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -0700992 public void interfaceClassDataActivityChanged(String label, boolean active) {
993 int deviceType = Integer.parseInt(label);
994 sendDataActivityBroadcast(deviceType, active);
995 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700996 };
Haoyu Baib5da5752012-06-20 14:29:57 -0700997
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700998 /**
999 * Used to notice when the calling process dies so we can self-expire
1000 *
1001 * Also used to know if the process has cleaned up after itself when
1002 * our auto-expire timer goes off. The timer has a link to an object.
1003 *
1004 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001005 private class FeatureUser implements IBinder.DeathRecipient {
1006 int mNetworkType;
1007 String mFeature;
1008 IBinder mBinder;
1009 int mPid;
1010 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001011 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001012
1013 FeatureUser(int type, String feature, IBinder binder) {
1014 super();
1015 mNetworkType = type;
1016 mFeature = feature;
1017 mBinder = binder;
1018 mPid = getCallingPid();
1019 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001020 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001021
Robert Greenwalt2034b912009-08-12 16:08:25 -07001022 try {
1023 mBinder.linkToDeath(this, 0);
1024 } catch (RemoteException e) {
1025 binderDied();
1026 }
1027 }
1028
1029 void unlinkDeathRecipient() {
1030 mBinder.unlinkToDeath(this, 0);
1031 }
1032
1033 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001034 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001035 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1036 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001037 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001038 }
1039
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001040 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001041 if (VDBG) {
1042 log("ConnectivityService FeatureUser expire(" +
1043 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1044 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1045 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001046 stopUsingNetworkFeature(this, false);
1047 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001048
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001049 public boolean isSameUser(FeatureUser u) {
1050 if (u == null) return false;
1051
1052 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1053 }
1054
1055 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1056 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1057 TextUtils.equals(mFeature, feature)) {
1058 return true;
1059 }
1060 return false;
1061 }
1062
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001063 public String toString() {
1064 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1065 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1066 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001067 }
1068
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001069 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001070 public int startUsingNetworkFeature(int networkType, String feature,
1071 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001072 long startTime = 0;
1073 if (DBG) {
1074 startTime = SystemClock.elapsedRealtime();
1075 }
Wink Savillea7d56572011-09-21 11:05:43 -07001076 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001077 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1078 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001079 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001080 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001081 try {
1082 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1083 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001084 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001085 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001086
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001087 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001088
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001089 // TODO - move this into individual networktrackers
1090 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001091
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001092 if (mLockdownEnabled) {
1093 // Since carrier APNs usually aren't available from VPN
1094 // endpoint, mark them as unavailable.
1095 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1096 }
1097
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001098 if (mProtectedNetworks.contains(usedNetworkType)) {
1099 enforceConnectivityInternalPermission();
1100 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001101
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001102 // if UID is restricted, don't allow them to bring up metered APNs
1103 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1104 final int uidRules;
1105 synchronized (mRulesLock) {
1106 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1107 }
1108 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001109 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001110 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001111
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001112 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1113 if (network != null) {
1114 Integer currentPid = new Integer(getCallingPid());
1115 if (usedNetworkType != networkType) {
1116 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001117
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001118 if (ni.isAvailable() == false) {
1119 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1120 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001121 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001122 } else {
1123 // else make the attempt anyway - probably giving REQUEST_STARTED below
1124 if (DBG) {
1125 log("special network not available, but try anyway ni=" +
1126 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001127 }
1128 }
1129 }
1130
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001131 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001132
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001133 synchronized(this) {
1134 boolean addToList = true;
1135 if (restoreTimer < 0) {
1136 // In case there is no timer is specified for the feature,
1137 // make sure we don't add duplicate entry with the same request.
1138 for (FeatureUser u : mFeatureUsers) {
1139 if (u.isSameUser(f)) {
1140 // Duplicate user is found. Do not add.
1141 addToList = false;
1142 break;
1143 }
1144 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001145 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001146
1147 if (addToList) mFeatureUsers.add(f);
1148 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1149 // this gets used for per-pid dns when connected
1150 mNetRequestersPids[usedNetworkType].add(currentPid);
1151 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001152 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001153
1154 if (restoreTimer >= 0) {
1155 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1156 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1157 }
1158
1159 if ((ni.isConnectedOrConnecting() == true) &&
1160 !network.isTeardownRequested()) {
1161 if (ni.isConnected() == true) {
1162 final long token = Binder.clearCallingIdentity();
1163 try {
1164 // add the pid-specific dns
1165 handleDnsConfigurationChange(usedNetworkType);
1166 if (VDBG) log("special network already active");
1167 } finally {
1168 Binder.restoreCallingIdentity(token);
1169 }
Wink Saville64e3f782012-07-10 12:37:54 -07001170 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001171 }
1172 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001173 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001174 }
1175
1176 // check if the radio in play can make another contact
1177 // assume if cannot for now
1178
1179 if (DBG) {
1180 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1181 feature);
1182 }
1183 network.reconnect();
Wink Saville64e3f782012-07-10 12:37:54 -07001184 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001185 } else {
1186 // need to remember this unsupported request so we respond appropriately on stop
1187 synchronized(this) {
1188 mFeatureUsers.add(f);
1189 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1190 // this gets used for per-pid dns when connected
1191 mNetRequestersPids[usedNetworkType].add(currentPid);
1192 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001193 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001194 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001195 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001196 }
Wink Saville64e3f782012-07-10 12:37:54 -07001197 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001198 } finally {
1199 if (DBG) {
1200 final long execTime = SystemClock.elapsedRealtime() - startTime;
1201 if (execTime > 250) {
1202 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1203 } else {
1204 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1205 }
1206 }
1207 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001208 }
1209
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001210 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001211 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001212 enforceChangePermission();
1213
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001214 int pid = getCallingPid();
1215 int uid = getCallingUid();
1216
1217 FeatureUser u = null;
1218 boolean found = false;
1219
1220 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001221 for (FeatureUser x : mFeatureUsers) {
1222 if (x.isSameUser(pid, uid, networkType, feature)) {
1223 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001224 found = true;
1225 break;
1226 }
1227 }
1228 }
1229 if (found && u != null) {
1230 // stop regardless of how many other time this proc had called start
1231 return stopUsingNetworkFeature(u, true);
1232 } else {
1233 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001234 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001235 return 1;
1236 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001237 }
1238
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001239 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1240 int networkType = u.mNetworkType;
1241 String feature = u.mFeature;
1242 int pid = u.mPid;
1243 int uid = u.mUid;
1244
1245 NetworkStateTracker tracker = null;
1246 boolean callTeardown = false; // used to carry our decision outside of sync block
1247
Wink Savillea7d56572011-09-21 11:05:43 -07001248 if (VDBG) {
1249 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001250 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001251
The Android Open Source Project28527d22009-03-03 19:31:44 -08001252 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001253 if (DBG) {
1254 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1255 ", net is invalid");
1256 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001257 return -1;
1258 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001259
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001260 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1261 // sync block
1262 synchronized(this) {
1263 // check if this process still has an outstanding start request
1264 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001265 if (VDBG) {
1266 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1267 ", ignoring");
1268 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001269 return 1;
1270 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001271 u.unlinkDeathRecipient();
1272 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1273 // If we care about duplicate requests, check for that here.
1274 //
1275 // This is done to support the extension of a request - the app
1276 // can request we start the network feature again and renew the
1277 // auto-shutoff delay. Normal "stop" calls from the app though
1278 // do not pay attention to duplicate requests - in effect the
1279 // API does not refcount and a single stop will counter multiple starts.
1280 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001281 for (FeatureUser x : mFeatureUsers) {
1282 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001283 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001284 return 1;
1285 }
1286 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001287 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001288
repo syncf5de5572011-07-29 23:55:49 -07001289 // TODO - move to individual network trackers
1290 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1291
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001292 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001293 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001294 if (DBG) {
1295 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1296 " no known tracker for used net type " + usedNetworkType);
1297 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001298 return -1;
1299 }
1300 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001301 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001302 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001303 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001304 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001305 if (VDBG) {
1306 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1307 " others still using it");
1308 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001309 return 1;
1310 }
1311 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001312 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001313 if (DBG) {
1314 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1315 " not a known feature - dropping");
1316 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001317 }
1318 }
Wink Savillea7d56572011-09-21 11:05:43 -07001319
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001320 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001321 if (DBG) {
1322 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1323 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001324 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001325 return 1;
1326 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001327 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001328 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001329 }
1330
1331 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001332 * @deprecated use requestRouteToHostAddress instead
1333 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001334 * Ensure that a network route exists to deliver traffic to the specified
1335 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001336 * @param networkType the type of the network over which traffic to the
1337 * specified host is to be routed
1338 * @param hostAddress the IP address of the host to which the route is
1339 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001340 * @return {@code true} on success, {@code false} on failure
1341 */
1342 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001343 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1344
1345 if (inetAddress == null) {
1346 return false;
1347 }
1348
1349 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1350 }
1351
1352 /**
1353 * Ensure that a network route exists to deliver traffic to the specified
1354 * host via the specified network interface.
1355 * @param networkType the type of the network over which traffic to the
1356 * specified host is to be routed
1357 * @param hostAddress the IP address of the host to which the route is
1358 * desired
1359 * @return {@code true} on success, {@code false} on failure
1360 */
1361 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001362 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001363 if (mProtectedNetworks.contains(networkType)) {
1364 enforceConnectivityInternalPermission();
1365 }
1366
The Android Open Source Project28527d22009-03-03 19:31:44 -08001367 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001368 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001369 return false;
1370 }
1371 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001372 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001373
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001374 if (tracker == null || (netState != DetailedState.CONNECTED &&
1375 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001376 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001377 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001378 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001379 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001380 }
1381 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001382 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001383 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001384 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001385 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001386 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -07001387 return addRouteToAddress(lp, addr);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001388 } catch (UnknownHostException e) {
1389 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1390 } finally {
1391 Binder.restoreCallingIdentity(token);
1392 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001393 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001394 }
1395
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001396 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1397 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001398 }
1399
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001400 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1401 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001402 }
1403
Robert Greenwalt98107422011-07-22 11:55:33 -07001404 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001405 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001406 }
1407
1408 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001409 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001410 }
1411
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001412 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1413 boolean toDefaultTable) {
Robert Greenwalt98107422011-07-22 11:55:33 -07001414 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1415 if (bestRoute == null) {
1416 bestRoute = RouteInfo.makeHostRoute(addr);
1417 } else {
1418 if (bestRoute.getGateway().equals(addr)) {
1419 // if there is no better route, add the implied hostroute for our gateway
1420 bestRoute = RouteInfo.makeHostRoute(addr);
1421 } else {
1422 // if we will connect to this through another route, add a direct route
1423 // to it's gateway
1424 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1425 }
1426 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001427 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001428 }
1429
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001430 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001431 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001432 if ((ifaceName == null) || (lp == null) || (r == null)) {
1433 if (DBG) log("modifyRoute got unexpected null: " + ifaceName + ", " + lp + ", " + r);
1434 return false;
1435 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001436
1437 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001438 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001439 return false;
1440 }
1441
1442 if (r.isHostRoute() == false) {
1443 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1444 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001445 if (bestRoute.getGateway().equals(r.getGateway())) {
1446 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001447 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001448 } else {
1449 // if we will connect to our gateway through another route, add a direct
1450 // route to it's gateway
1451 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001452 }
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001453 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001454 }
1455 }
1456 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001457 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001458 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001459 if (toDefaultTable) {
1460 mAddedRoutes.add(r); // only track default table - only one apps can effect
1461 mNetd.addRoute(ifaceName, r);
1462 } else {
1463 mNetd.addSecondaryRoute(ifaceName, r);
1464 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001465 } catch (Exception e) {
1466 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001467 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001468 return false;
1469 }
1470 } else {
1471 // if we remove this one and there are no more like it, then refcount==0 and
1472 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001473 if (toDefaultTable) {
1474 mAddedRoutes.remove(r);
1475 if (mAddedRoutes.contains(r) == false) {
1476 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1477 try {
1478 mNetd.removeRoute(ifaceName, r);
1479 } catch (Exception e) {
1480 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001481 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001482 return false;
1483 }
1484 } else {
1485 if (VDBG) log("not removing " + r + " as it's still in use");
1486 }
1487 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001488 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001489 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001490 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001491 } catch (Exception e) {
1492 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001493 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001494 return false;
1495 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001496 }
1497 }
1498 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001499 }
1500
1501 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001502 * @see ConnectivityManager#getMobileDataEnabled()
1503 */
1504 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001505 // TODO: This detail should probably be in DataConnectionTracker's
1506 // which is where we store the value and maybe make this
1507 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001508 enforceAccessPermission();
1509 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1510 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001511 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001512 return retVal;
1513 }
1514
Robert Greenwalt34848c02011-03-25 13:09:25 -07001515 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001516 enforceConnectivityInternalPermission();
1517
Robert Greenwalt34848c02011-03-25 13:09:25 -07001518 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1519 (met ? ENABLED : DISABLED), networkType));
1520 }
1521
1522 private void handleSetDependencyMet(int networkType, boolean met) {
1523 if (mNetTrackers[networkType] != null) {
1524 if (DBG) {
1525 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1526 }
1527 mNetTrackers[networkType].setDependencyMet(met);
1528 }
1529 }
1530
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001531 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1532 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001533 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001534 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001535 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001536 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001537 }
1538
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001539 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001540 // skip update when we've already applied rules
1541 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1542 if (oldRules == uidRules) return;
1543
1544 mUidRules.put(uid, uidRules);
1545 }
1546
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001547 // TODO: notify UID when it has requested targeted updates
1548 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001549
1550 @Override
1551 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001552 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001553 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001554 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001555 }
1556
1557 synchronized (mRulesLock) {
1558 mMeteredIfaces.clear();
1559 for (String iface : meteredIfaces) {
1560 mMeteredIfaces.add(iface);
1561 }
1562 }
1563 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001564
1565 @Override
1566 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1567 // caller is NPMS, since we only register with them
1568 if (LOGD_RULES) {
1569 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1570 }
1571
1572 // kick off connectivity change broadcast for active network, since
1573 // global background policy change is radical.
1574 final int networkType = mActiveDefaultNetwork;
1575 if (isNetworkTypeValid(networkType)) {
1576 final NetworkStateTracker tracker = mNetTrackers[networkType];
1577 if (tracker != null) {
1578 final NetworkInfo info = tracker.getNetworkInfo();
1579 if (info != null && info.isConnected()) {
1580 sendConnectedBroadcast(info);
1581 }
1582 }
1583 }
1584 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001585 };
1586
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001587 /**
1588 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1589 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001590 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001591 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001592 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001593
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001594 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001595 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001596 }
1597
1598 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001599 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001600 if (VDBG) {
1601 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001602 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001603 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1604 }
tk.mun5eee1042012-01-06 10:43:52 +09001605 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1606 if (VDBG) {
1607 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1608 }
1609 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1610 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001611 }
1612
1613 @Override
1614 public void setPolicyDataEnable(int networkType, boolean enabled) {
1615 // only someone like NPMS should only be calling us
1616 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1617
1618 mHandler.sendMessage(mHandler.obtainMessage(
1619 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1620 }
1621
1622 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1623 if (isNetworkTypeValid(networkType)) {
1624 final NetworkStateTracker tracker = mNetTrackers[networkType];
1625 if (tracker != null) {
1626 tracker.setPolicyDataEnable(enabled);
1627 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001628 }
1629 }
1630
The Android Open Source Project28527d22009-03-03 19:31:44 -08001631 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001632 mContext.enforceCallingOrSelfPermission(
1633 android.Manifest.permission.ACCESS_NETWORK_STATE,
1634 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001635 }
1636
1637 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001638 mContext.enforceCallingOrSelfPermission(
1639 android.Manifest.permission.CHANGE_NETWORK_STATE,
1640 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001641 }
1642
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001643 // TODO Make this a special check when it goes public
1644 private void enforceTetherChangePermission() {
1645 mContext.enforceCallingOrSelfPermission(
1646 android.Manifest.permission.CHANGE_NETWORK_STATE,
1647 "ConnectivityService");
1648 }
1649
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001650 private void enforceTetherAccessPermission() {
1651 mContext.enforceCallingOrSelfPermission(
1652 android.Manifest.permission.ACCESS_NETWORK_STATE,
1653 "ConnectivityService");
1654 }
1655
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001656 private void enforceConnectivityInternalPermission() {
1657 mContext.enforceCallingOrSelfPermission(
1658 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1659 "ConnectivityService");
1660 }
1661
The Android Open Source Project28527d22009-03-03 19:31:44 -08001662 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001663 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1664 * network, we ignore it. If it is for the active network, we send out a
1665 * broadcast. But first, we check whether it might be possible to connect
1666 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001667 * @param info the {@code NetworkInfo} for the network
1668 */
1669 private void handleDisconnect(NetworkInfo info) {
1670
Robert Greenwalt2034b912009-08-12 16:08:25 -07001671 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001672
Robert Greenwalt2034b912009-08-12 16:08:25 -07001673 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Baie2462442012-06-28 15:26:19 -07001674
1675 // Remove idletimer previously setup in {@code handleConnect}
1676 removeDataActivityTracking(prevNetType);
1677
The Android Open Source Project28527d22009-03-03 19:31:44 -08001678 /*
1679 * If the disconnected network is not the active one, then don't report
1680 * this as a loss of connectivity. What probably happened is that we're
1681 * getting the disconnect for a network that we explicitly disabled
1682 * in accordance with network preference policies.
1683 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001684 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001685 List pids = mNetRequestersPids[prevNetType];
1686 for (int i = 0; i<pids.size(); i++) {
1687 Integer pid = (Integer)pids.get(i);
1688 // will remove them because the net's no longer connected
1689 // need to do this now as only now do we know the pids and
1690 // can properly null things that are no longer referenced.
1691 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001692 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001693 }
1694
The Android Open Source Project28527d22009-03-03 19:31:44 -08001695 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1696 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
Jeff Sharkey47905d12012-08-06 11:41:50 -07001697 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001698 if (info.isFailover()) {
1699 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1700 info.setFailover(false);
1701 }
1702 if (info.getReason() != null) {
1703 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1704 }
1705 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001706 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1707 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001708 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001709
Robert Greenwalt34848c02011-03-25 13:09:25 -07001710 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001711 tryFailover(prevNetType);
1712 if (mActiveDefaultNetwork != -1) {
1713 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001714 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1715 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001716 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001717 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1718 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001719 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001720 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001721
1722 // Reset interface if no other connections are using the same interface
1723 boolean doReset = true;
1724 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1725 if (linkProperties != null) {
1726 String oldIface = linkProperties.getInterfaceName();
1727 if (TextUtils.isEmpty(oldIface) == false) {
1728 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1729 if (networkStateTracker == null) continue;
1730 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1731 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1732 LinkProperties l = networkStateTracker.getLinkProperties();
1733 if (l == null) continue;
1734 if (oldIface.equals(l.getInterfaceName())) {
1735 doReset = false;
1736 break;
1737 }
1738 }
1739 }
1740 }
1741 }
1742
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001743 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001744 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001745
Jeff Sharkey971cd162011-08-29 16:02:57 -07001746 final Intent immediateIntent = new Intent(intent);
1747 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1748 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001749 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001750 /*
1751 * If the failover network is already connected, then immediately send
1752 * out a followup broadcast indicating successful failover
1753 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001754 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001755 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1756 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001757 }
1758 }
1759
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001760 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001761 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001762 * If this is a default network, check if other defaults are available.
1763 * Try to reconnect on all available and let them hash it out when
1764 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001765 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001766 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001767 if (mActiveDefaultNetwork == prevNetType) {
1768 mActiveDefaultNetwork = -1;
1769 }
1770
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001771 // don't signal a reconnect for anything lower or equal priority than our
1772 // current connected default
1773 // TODO - don't filter by priority now - nice optimization but risky
1774// int currentPriority = -1;
1775// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001776// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001777// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001778 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001779 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001780 if (mNetConfigs[checkType] == null) continue;
1781 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001782 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001783
1784// Enabling the isAvailable() optimization caused mobile to not get
1785// selected if it was in the middle of error handling. Specifically
1786// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1787// would not be available and we wouldn't get connected to anything.
1788// So removing the isAvailable() optimization below for now. TODO: This
1789// optimization should work and we need to investigate why it doesn't work.
1790// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1791// complete before it is really complete.
1792// if (!mNetTrackers[checkType].isAvailable()) continue;
1793
Robert Greenwalt34848c02011-03-25 13:09:25 -07001794// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001795
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001796 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1797 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1798 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1799 checkInfo.setFailover(true);
1800 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001801 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001802 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001803 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001804 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001805 }
1806
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001807 public void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001808 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1809 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001810 }
1811
Wink Saville4f0de1e2011-08-04 15:01:58 -07001812 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001813 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1814 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001815 }
1816
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001817 private void sendInetConditionBroadcast(NetworkInfo info) {
1818 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1819 }
1820
Wink Saville4f0de1e2011-08-04 15:01:58 -07001821 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001822 if (mLockdownTracker != null) {
1823 info = mLockdownTracker.augmentNetworkInfo(info);
1824 }
1825
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001826 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001827 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
Jeff Sharkey47905d12012-08-06 11:41:50 -07001828 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001829 if (info.isFailover()) {
1830 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1831 info.setFailover(false);
1832 }
1833 if (info.getReason() != null) {
1834 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1835 }
1836 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001837 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1838 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001839 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001840 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001841 return intent;
1842 }
1843
1844 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1845 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1846 }
1847
1848 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1849 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001850 }
1851
Haoyu Baib5da5752012-06-20 14:29:57 -07001852 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1853 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1854 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1855 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborne588ca12012-09-04 18:48:37 -07001856 final long ident = Binder.clearCallingIdentity();
1857 try {
1858 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1859 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1860 } finally {
1861 Binder.restoreCallingIdentity(ident);
1862 }
Haoyu Baib5da5752012-06-20 14:29:57 -07001863 }
1864
The Android Open Source Project28527d22009-03-03 19:31:44 -08001865 /**
1866 * Called when an attempt to fail over to another network has failed.
1867 * @param info the {@link NetworkInfo} for the failed network
1868 */
1869 private void handleConnectionFailure(NetworkInfo info) {
1870 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001871
Robert Greenwalt2034b912009-08-12 16:08:25 -07001872 String reason = info.getReason();
1873 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001874
Robert Greenwalte981bc52010-10-08 16:35:52 -07001875 String reasonText;
1876 if (reason == null) {
1877 reasonText = ".";
1878 } else {
1879 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001880 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001881 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001882
1883 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1884 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
Jeff Sharkey47905d12012-08-06 11:41:50 -07001885 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001886 if (getActiveNetworkInfo() == null) {
1887 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1888 }
1889 if (reason != null) {
1890 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1891 }
1892 if (extraInfo != null) {
1893 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1894 }
1895 if (info.isFailover()) {
1896 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1897 info.setFailover(false);
1898 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001899
Robert Greenwalt34848c02011-03-25 13:09:25 -07001900 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001901 tryFailover(info.getType());
1902 if (mActiveDefaultNetwork != -1) {
1903 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001904 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1905 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001906 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001907 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1908 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001909 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001910
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001911 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07001912
1913 final Intent immediateIntent = new Intent(intent);
1914 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1915 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001916 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001917 /*
1918 * If the failover network is already connected, then immediately send
1919 * out a followup broadcast indicating successful failover
1920 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001921 if (mActiveDefaultNetwork != -1) {
1922 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001923 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001924 }
1925
1926 private void sendStickyBroadcast(Intent intent) {
1927 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001928 if (!mSystemReady) {
1929 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001930 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001931 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07001932 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001933 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07001934 }
1935
Dianne Hackborne588ca12012-09-04 18:48:37 -07001936 final long ident = Binder.clearCallingIdentity();
1937 try {
1938 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1939 } finally {
1940 Binder.restoreCallingIdentity(ident);
1941 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001942 }
1943 }
1944
Wink Saville4f0de1e2011-08-04 15:01:58 -07001945 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1946 if (delayMs <= 0) {
1947 sendStickyBroadcast(intent);
1948 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001949 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001950 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1951 + intent.getAction());
1952 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07001953 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1954 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1955 }
1956 }
1957
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001958 void systemReady() {
1959 synchronized(this) {
1960 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001961 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07001962 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08001963 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001964 }
1965 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001966 // load the global proxy at startup
1967 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001968
1969 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1970 // for user to unlock device.
1971 if (!updateLockdownVpn()) {
1972 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1973 mContext.registerReceiver(mUserPresentReceiver, filter);
1974 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001975 }
1976
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001977 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1978 @Override
1979 public void onReceive(Context context, Intent intent) {
1980 // Try creating lockdown tracker, since user present usually means
1981 // unlocked keystore.
1982 if (updateLockdownVpn()) {
1983 mContext.unregisterReceiver(this);
1984 }
1985 }
1986 };
1987
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001988 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
1989 if ((type != mNetworkPreference &&
1990 mNetConfigs[mActiveDefaultNetwork].priority >
1991 mNetConfigs[type].priority) ||
1992 mNetworkPreference == mActiveDefaultNetwork) return false;
1993 return true;
1994 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001995
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001996 private void handleConnect(NetworkInfo info) {
1997 final int newNetType = info.getType();
1998
1999 setupDataActivityTracking(newNetType);
Haoyu Baie2462442012-06-28 15:26:19 -07002000
The Android Open Source Project28527d22009-03-03 19:31:44 -08002001 // snapshot isFailover, because sendConnectedBroadcast() resets it
2002 boolean isFailover = info.isFailover();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002003 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002004 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002005
Robert Greenwalt2034b912009-08-12 16:08:25 -07002006 // if this is a default net and other default is running
2007 // kill the one not preferred
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002008 if (mNetConfigs[newNetType].isDefault()) {
2009 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2010 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002011 // tear down the other
2012 NetworkStateTracker otherNet =
2013 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002014 if (DBG) {
2015 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002016 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002017 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002018 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002019 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002020 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002021 return;
2022 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002023 } else {
2024 // don't accept this one
2025 if (VDBG) {
2026 log("Not broadcasting CONNECT_ACTION " +
2027 "to torn down network " + info.getTypeName());
2028 }
2029 teardown(thisNet);
2030 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002031 }
2032 }
2033 synchronized (ConnectivityService.this) {
2034 // have a new default network, release the transition wakelock in a second
2035 // if it's held. The second pause is to allow apps to reconnect over the
2036 // new network
2037 if (mNetTransitionWakeLock.isHeld()) {
2038 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002039 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002040 mNetTransitionWakeLockSerialNumber, 0),
2041 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002042 }
2043 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002044 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002045 // this will cause us to come up initially as unconnected and switching
2046 // to connected after our normal pause unless somebody reports us as reall
2047 // disconnected
2048 mDefaultInetConditionPublished = 0;
2049 mDefaultConnectionSequence++;
2050 mInetConditionChangeInFlight = false;
2051 // Don't do this - if we never sign in stay, grey
2052 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002053 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002054 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002055 updateNetworkSettings(thisNet);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002056 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002057 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002058
2059 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002060 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002061 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002062 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002063 } catch (RemoteException e) {
2064 // ignored; service lives in system_server
2065 }
2066 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002067 }
2068
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002069 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2070 if (DBG) log("Captive portal check " + info);
2071 int type = info.getType();
2072 final NetworkStateTracker thisNet = mNetTrackers[type];
2073 if (mNetConfigs[type].isDefault()) {
2074 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2075 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2076 if (DBG) log("Captive check on " + info.getTypeName());
2077 mCaptivePortalTracker = CaptivePortalTracker.detect(mContext, info,
2078 ConnectivityService.this);
2079 return;
2080 } else {
2081 if (DBG) log("Tear down low priority net " + info.getTypeName());
2082 teardown(thisNet);
2083 return;
2084 }
2085 }
2086 }
2087
2088 thisNet.captivePortalCheckComplete();
2089 }
2090
2091 /** @hide */
2092 public void captivePortalCheckComplete(NetworkInfo info) {
2093 mNetTrackers[info.getType()].captivePortalCheckComplete();
2094 mCaptivePortalTracker = null;
2095 }
2096
The Android Open Source Project28527d22009-03-03 19:31:44 -08002097 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002098 * Setup data activity tracking for the given network interface.
2099 *
2100 * Every {@code setupDataActivityTracking} should be paired with a
2101 * {@link removeDataActivityTracking} for cleanup.
2102 */
2103 private void setupDataActivityTracking(int type) {
2104 final NetworkStateTracker thisNet = mNetTrackers[type];
2105 final String iface = thisNet.getLinkProperties().getInterfaceName();
2106
2107 final int timeout;
2108
2109 if (ConnectivityManager.isNetworkTypeMobile(type)) {
2110 timeout = Settings.Secure.getInt(mContext.getContentResolver(),
2111 Settings.Secure.DATA_ACTIVITY_TIMEOUT_MOBILE,
2112 0);
2113 // Canonicalize mobile network type
2114 type = ConnectivityManager.TYPE_MOBILE;
2115 } else if (ConnectivityManager.TYPE_WIFI == type) {
2116 timeout = Settings.Secure.getInt(mContext.getContentResolver(),
2117 Settings.Secure.DATA_ACTIVITY_TIMEOUT_WIFI,
2118 0);
2119 } else {
2120 // do not track any other networks
2121 timeout = 0;
2122 }
2123
2124 if (timeout > 0 && iface != null) {
2125 try {
2126 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2127 } catch (RemoteException e) {
2128 }
2129 }
2130 }
2131
2132 /**
2133 * Remove data activity tracking when network disconnects.
2134 */
2135 private void removeDataActivityTracking(int type) {
2136 final NetworkStateTracker net = mNetTrackers[type];
2137 final String iface = net.getLinkProperties().getInterfaceName();
2138
2139 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2140 ConnectivityManager.TYPE_WIFI == type)) {
2141 try {
2142 // the call fails silently if no idletimer setup for this interface
2143 mNetd.removeIdleTimer(iface);
2144 } catch (RemoteException e) {
2145 }
2146 }
2147 }
2148
2149 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002150 * After a change in the connectivity state of a network. We're mainly
2151 * concerned with making sure that the list of DNS servers is set up
2152 * according to which networks are connected, and ensuring that the
2153 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002154 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002155 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002156 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2157
The Android Open Source Project28527d22009-03-03 19:31:44 -08002158 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002159 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002160 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002161 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002162 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002163
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002164 LinkProperties curLp = mCurrentLinkProperties[netType];
2165 LinkProperties newLp = null;
2166
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002167 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002168 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002169 if (VDBG) {
2170 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2171 " doReset=" + doReset + " resetMask=" + resetMask +
2172 "\n curLp=" + curLp +
2173 "\n newLp=" + newLp);
2174 }
2175
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002176 if (curLp != null) {
2177 if (curLp.isIdenticalInterfaceName(newLp)) {
2178 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2179 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2180 for (LinkAddress linkAddr : car.removed) {
2181 if (linkAddr.getAddress() instanceof Inet4Address) {
2182 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2183 }
2184 if (linkAddr.getAddress() instanceof Inet6Address) {
2185 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2186 }
Wink Saville051a6642011-07-13 13:44:13 -07002187 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002188 if (DBG) {
2189 log("handleConnectivityChange: addresses changed" +
2190 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2191 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002192 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002193 } else {
2194 if (DBG) {
2195 log("handleConnectivityChange: address are the same reset per doReset" +
2196 " linkProperty[" + netType + "]:" +
2197 " resetMask=" + resetMask);
2198 }
Wink Saville051a6642011-07-13 13:44:13 -07002199 }
2200 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002201 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002202 if (DBG) {
2203 log("handleConnectivityChange: interface not not equivalent reset both" +
2204 " linkProperty[" + netType + "]:" +
2205 " resetMask=" + resetMask);
2206 }
Wink Saville051a6642011-07-13 13:44:13 -07002207 }
Wink Saville051a6642011-07-13 13:44:13 -07002208 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002209 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002210 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002211 }
2212 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002213 if (VDBG) {
2214 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2215 " doReset=" + doReset + " resetMask=" + resetMask +
2216 "\n curLp=" + curLp +
2217 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002218 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002219 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002220 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07002221 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002222
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002223 if (resetMask != 0 || resetDns) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002224 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
2225 if (linkProperties != null) {
2226 String iface = linkProperties.getInterfaceName();
2227 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002228 if (resetMask != 0) {
Robert Greenwalt8d777252011-08-15 12:31:55 -07002229 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2230 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002231
2232 // Tell VPN the interface is down. It is a temporary
2233 // but effective fix to make VPN aware of the change.
2234 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2235 mVpn.interfaceStatusChanged(iface, false);
2236 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002237 }
2238 if (resetDns) {
Wink Savillea7d56572011-09-21 11:05:43 -07002239 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002240 try {
2241 mNetd.flushInterfaceDnsCache(iface);
2242 } catch (Exception e) {
2243 // never crash - catch them all
Wink Savillea7d56572011-09-21 11:05:43 -07002244 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002245 }
2246 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002247 }
2248 }
2249 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002250
2251 // TODO: Temporary notifying upstread change to Tethering.
2252 // @see bug/4455071
2253 /** Notify TetheringService if interface name has been changed. */
2254 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002255 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002256 if (isTetheringSupported()) {
2257 mTethering.handleTetherIfaceChange();
2258 }
2259 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002260 }
2261
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002262 /**
2263 * Add and remove routes using the old properties (null if not previously connected),
2264 * new properties (null if becoming disconnected). May even be double null, which
2265 * is a noop.
2266 * Uses isLinkDefault to determine if default routes should be set or conversely if
2267 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002268 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002269 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002270 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2271 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002272 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002273 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2274 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002275 if (curLp != null) {
2276 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002277 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002278 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002279 } else if (newLp != null) {
2280 routeDiff.added = newLp.getRoutes();
2281 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002282 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002283
Robert Greenwalt8d777252011-08-15 12:31:55 -07002284 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2285
Robert Greenwalt98107422011-07-22 11:55:33 -07002286 for (RouteInfo r : routeDiff.removed) {
2287 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002288 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2289 }
2290 if (isLinkDefault == false) {
2291 // remove from a secondary route table
2292 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002293 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002294 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002295
Robert Greenwalt98107422011-07-22 11:55:33 -07002296 for (RouteInfo r : routeDiff.added) {
2297 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002298 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002299 } else {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002300 // add to a secondary route table
2301 addRoute(newLp, r, TO_SECONDARY_TABLE);
2302
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002303 // many radios add a default route even when we don't want one.
2304 // remove the default route unless somebody else has asked for it
2305 String ifaceName = newLp.getInterfaceName();
2306 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002307 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002308 try {
2309 mNetd.removeRoute(ifaceName, r);
2310 } catch (Exception e) {
2311 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002312 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt08ae9bc2011-08-09 16:52:58 -07002313 }
2314 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002315 }
2316 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002317
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002318 if (!isLinkDefault) {
2319 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002320 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002321 // routes changed - remove all old dns entries and add new
2322 if (curLp != null) {
2323 for (InetAddress oldDns : curLp.getDnses()) {
2324 removeRouteToAddress(curLp, oldDns);
2325 }
2326 }
2327 if (newLp != null) {
2328 for (InetAddress newDns : newLp.getDnses()) {
2329 addRouteToAddress(newLp, newDns);
2330 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002331 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002332 } else {
2333 // no change in routes, check for change in dns themselves
2334 for (InetAddress oldDns : dnsDiff.removed) {
2335 removeRouteToAddress(curLp, oldDns);
2336 }
2337 for (InetAddress newDns : dnsDiff.added) {
2338 addRouteToAddress(newLp, newDns);
2339 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002340 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002341 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002342 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002343 }
2344
2345
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002346 /**
2347 * Reads the network specific TCP buffer sizes from SystemProperties
2348 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2349 * wide use
2350 */
2351 public void updateNetworkSettings(NetworkStateTracker nt) {
2352 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002353 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002354
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002355 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002356 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002357
2358 // Setting to default values so we won't be stuck to previous values
2359 key = "net.tcp.buffersize.default";
2360 bufferSizes = SystemProperties.get(key);
2361 }
2362
2363 // Set values in kernel
2364 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002365 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002366 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002367 + "] which comes from [" + key + "]");
2368 }
2369 setBufferSize(bufferSizes);
2370 }
2371 }
2372
2373 /**
2374 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2375 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2376 *
2377 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2378 * writeMin, writeInitial, writeMax"
2379 */
2380 private void setBufferSize(String bufferSizes) {
2381 try {
2382 String[] values = bufferSizes.split(",");
2383
2384 if (values.length == 6) {
2385 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002386 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2387 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2388 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2389 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2390 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2391 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002392 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002393 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002394 }
2395 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002396 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002397 }
2398 }
2399
Robert Greenwalt2034b912009-08-12 16:08:25 -07002400 /**
2401 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2402 * on the highest priority active net which this process requested.
2403 * If there aren't any, clear it out
2404 */
2405 private void reassessPidDns(int myPid, boolean doBump)
2406 {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002407 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002408 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002409 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002410 continue;
2411 }
2412 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002413 if (nt.getNetworkInfo().isConnected() &&
2414 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002415 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002416 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002417 List pids = mNetRequestersPids[i];
2418 for (int j=0; j<pids.size(); j++) {
2419 Integer pid = (Integer)pids.get(j);
2420 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002421 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002422 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002423 if (doBump) {
2424 bumpDns();
2425 }
2426 return;
2427 }
2428 }
2429 }
2430 }
2431 // nothing found - delete
2432 for (int i = 1; ; i++) {
2433 String prop = "net.dns" + i + "." + myPid;
2434 if (SystemProperties.get(prop).length() == 0) {
2435 if (doBump) {
2436 bumpDns();
2437 }
2438 return;
2439 }
2440 SystemProperties.set(prop, "");
2441 }
2442 }
2443
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002444 // return true if results in a change
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002445 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002446 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002447 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002448 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002449 String dnsString = dns.getHostAddress();
2450 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2451 changed = true;
yoonsung.nam48d18332012-03-02 19:56:16 +09002452 SystemProperties.set("net.dns" + j + "." + pid, dns.getHostAddress());
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002453 }
yoonsung.nam48d18332012-03-02 19:56:16 +09002454 j++;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002455 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002456 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002457 }
2458
2459 private void bumpDns() {
2460 /*
2461 * Bump the property that tells the name resolver library to reread
2462 * the DNS server list from the properties.
2463 */
2464 String propVal = SystemProperties.get("net.dnschange");
2465 int n = 0;
2466 if (propVal.length() != 0) {
2467 try {
2468 n = Integer.parseInt(propVal);
2469 } catch (NumberFormatException e) {}
2470 }
2471 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07002472 /*
2473 * Tell the VMs to toss their DNS caches
2474 */
2475 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2476 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002477 /*
2478 * Connectivity events can happen before boot has completed ...
2479 */
2480 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002481 final long ident = Binder.clearCallingIdentity();
2482 try {
2483 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2484 } finally {
2485 Binder.restoreCallingIdentity(ident);
2486 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002487 }
2488
Chia-chi Yehcc844502011-07-14 18:01:57 -07002489 // Caller must grab mDnsLock.
Robert Greenwaltfce71862011-07-25 16:06:25 -07002490 private boolean updateDns(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002491 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002492 boolean changed = false;
2493 int last = 0;
2494 if (dnses.size() == 0 && mDefaultDns != null) {
2495 ++last;
2496 String value = mDefaultDns.getHostAddress();
2497 if (!value.equals(SystemProperties.get("net.dns1"))) {
2498 if (DBG) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002499 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002500 }
2501 changed = true;
2502 SystemProperties.set("net.dns1", value);
2503 }
2504 } else {
2505 for (InetAddress dns : dnses) {
2506 ++last;
2507 String key = "net.dns" + last;
2508 String value = dns.getHostAddress();
2509 if (!changed && value.equals(SystemProperties.get(key))) {
2510 continue;
2511 }
Robert Greenwalt78f28112011-08-02 17:18:41 -07002512 if (VDBG) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002513 log("adding dns " + value + " for " + network);
2514 }
2515 changed = true;
2516 SystemProperties.set(key, value);
2517 }
2518 }
2519 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2520 String key = "net.dns" + i;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002521 if (VDBG) log("erasing " + key);
Chia-chi Yehcc844502011-07-14 18:01:57 -07002522 changed = true;
2523 SystemProperties.set(key, "");
2524 }
2525 mNumDnsEntries = last;
2526
Robert Greenwaltfce71862011-07-25 16:06:25 -07002527 if (changed) {
2528 try {
2529 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2530 mNetd.setDefaultInterfaceForDns(iface);
2531 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002532 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002533 }
2534 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002535 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2536 SystemProperties.set("net.dns.search", domains);
2537 changed = true;
2538 }
2539 return changed;
2540 }
2541
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002542 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002543 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002544 NetworkStateTracker nt = mNetTrackers[netType];
2545 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002546 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002547 if (p == null) return;
2548 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002549 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07002550 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002551 String network = nt.getNetworkInfo().getTypeName();
2552 synchronized (mDnsLock) {
2553 if (!mDnsOverridden) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002554 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalt94daa182010-09-01 11:34:05 -07002555 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002556 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002557 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002558 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002559 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltfce71862011-07-25 16:06:25 -07002560 NetworkUtils.makeStrings(dnses));
2561 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002562 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002563 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002564 // set per-pid dns for attached secondary nets
2565 List pids = mNetRequestersPids[netType];
2566 for (int y=0; y< pids.size(); y++) {
2567 Integer pid = (Integer)pids.get(y);
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002568 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002569 }
2570 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08002571 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002572 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002573 }
2574
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002575 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002576 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2577 NETWORK_RESTORE_DELAY_PROP_NAME);
2578 if(restoreDefaultNetworkDelayStr != null &&
2579 restoreDefaultNetworkDelayStr.length() != 0) {
2580 try {
2581 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2582 } catch (NumberFormatException e) {
2583 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002584 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002585 // if the system property isn't set, use the value for the apn type
2586 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2587
2588 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2589 (mNetConfigs[networkType] != null)) {
2590 ret = mNetConfigs[networkType].restoreTime;
2591 }
2592 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002593 }
2594
2595 @Override
2596 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002597 if (mContext.checkCallingOrSelfPermission(
2598 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002599 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002600 pw.println("Permission Denial: can't dump ConnectivityService " +
2601 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2602 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002603 return;
2604 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002605 pw.println();
2606 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002607 if (nst != null) {
2608 if (nst.getNetworkInfo().isConnected()) {
2609 pw.println("Active network: " + nst.getNetworkInfo().
2610 getTypeName());
2611 }
2612 pw.println(nst.getNetworkInfo());
2613 pw.println(nst);
2614 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002615 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002616 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002617
2618 pw.println("Network Requester Pids:");
2619 for (int net : mPriorityList) {
2620 String pidString = net + ": ";
2621 for (Object pid : mNetRequestersPids[net]) {
2622 pidString = pidString + pid.toString() + ", ";
2623 }
2624 pw.println(pidString);
2625 }
2626 pw.println();
2627
2628 pw.println("FeatureUsers:");
2629 for (Object requester : mFeatureUsers) {
2630 pw.println(requester.toString());
2631 }
2632 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002633
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002634 synchronized (this) {
2635 pw.println("NetworkTranstionWakeLock is currently " +
2636 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2637 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2638 }
2639 pw.println();
2640
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002641 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002642
2643 if (mInetLog != null) {
2644 pw.println();
2645 pw.println("Inet condition reports:");
2646 for(int i = 0; i < mInetLog.size(); i++) {
2647 pw.println(mInetLog.get(i));
2648 }
2649 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002650 }
2651
Robert Greenwalt2034b912009-08-12 16:08:25 -07002652 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002653 private class NetworkStateTrackerHandler extends Handler {
2654 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002655 super(looper);
2656 }
2657
The Android Open Source Project28527d22009-03-03 19:31:44 -08002658 @Override
2659 public void handleMessage(Message msg) {
2660 NetworkInfo info;
2661 switch (msg.what) {
2662 case NetworkStateTracker.EVENT_STATE_CHANGED:
2663 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002664 int type = info.getType();
2665 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002666
Wink Savillea7d56572011-09-21 11:05:43 -07002667 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2668 (state == NetworkInfo.State.DISCONNECTED)) {
2669 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002670 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002671 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002672 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002673
2674 // Connectivity state changed:
Robert Greenwalt310fa082012-04-25 13:45:02 -07002675 // [31-14] Reserved for future use
2676 // [13-10] Network subtype (for mobile network, as defined
Robert Greenwalt0659da32009-07-16 17:21:39 -07002677 // by TelephonyManager)
Robert Greenwalt310fa082012-04-25 13:45:02 -07002678 // [9-4] Detailed state ordinal (as defined by
Robert Greenwalt0659da32009-07-16 17:21:39 -07002679 // NetworkInfo.DetailedState)
Robert Greenwalt310fa082012-04-25 13:45:02 -07002680 // [3-0] Network type (as defined by ConnectivityManager)
2681 int eventLogParam = (info.getType() & 0xf) |
2682 ((info.getDetailedState().ordinal() & 0x3f) << 4) |
2683 (info.getSubtype() << 10);
Doug Zongker2fc96232009-12-04 10:31:43 -08002684 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002685 eventLogParam);
2686
2687 if (info.getDetailedState() ==
2688 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002689 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002690 } else if (info.getDetailedState() ==
2691 DetailedState.CAPTIVE_PORTAL_CHECK) {
2692 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002693 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002694 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002695 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002696 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002697 // the logic here is, handle SUSPENDED the same as
2698 // DISCONNECTED. The only difference being we are
2699 // broadcasting an intent with NetworkInfo that's
2700 // suspended. This allows the applications an
2701 // opportunity to handle DISCONNECTED and SUSPENDED
2702 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002703 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002704 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002705 handleConnect(info);
2706 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002707 if (mLockdownTracker != null) {
2708 mLockdownTracker.onNetworkInfoChanged(info);
2709 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002710 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002711 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002712 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002713 // TODO: Temporary allowing network configuration
2714 // change not resetting sockets.
2715 // @see bug/4455071
2716 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002717 break;
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07002718 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2719 info = (NetworkInfo) msg.obj;
2720 type = info.getType();
2721 updateNetworkSettings(mNetTrackers[type]);
2722 break;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002723 }
2724 }
2725 }
2726
2727 private class InternalHandler extends Handler {
2728 public InternalHandler(Looper looper) {
2729 super(looper);
2730 }
2731
2732 @Override
2733 public void handleMessage(Message msg) {
2734 NetworkInfo info;
2735 switch (msg.what) {
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002736 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002737 String causedBy = null;
2738 synchronized (ConnectivityService.this) {
2739 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2740 mNetTransitionWakeLock.isHeld()) {
2741 mNetTransitionWakeLock.release();
2742 causedBy = mNetTransitionWakeLockCausedBy;
2743 }
2744 }
2745 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002746 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002747 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002748 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002749 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002750 FeatureUser u = (FeatureUser)msg.obj;
2751 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002752 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002753 case EVENT_INET_CONDITION_CHANGE:
2754 {
2755 int netType = msg.arg1;
2756 int condition = msg.arg2;
2757 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002758 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002759 }
2760 case EVENT_INET_CONDITION_HOLD_END:
2761 {
2762 int netType = msg.arg1;
2763 int sequence = msg.arg2;
2764 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002765 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002766 }
2767 case EVENT_SET_NETWORK_PREFERENCE:
2768 {
2769 int preference = msg.arg1;
2770 handleSetNetworkPreference(preference);
2771 break;
2772 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002773 case EVENT_SET_MOBILE_DATA:
2774 {
2775 boolean enabled = (msg.arg1 == ENABLED);
2776 handleSetMobileData(enabled);
2777 break;
2778 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002779 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2780 {
2781 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002782 break;
2783 }
2784 case EVENT_SET_DEPENDENCY_MET:
2785 {
2786 boolean met = (msg.arg1 == ENABLED);
2787 handleSetDependencyMet(msg.arg2, met);
2788 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002789 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002790 case EVENT_RESTORE_DNS:
2791 {
2792 if (mActiveDefaultNetwork != -1) {
2793 handleDnsConfigurationChange(mActiveDefaultNetwork);
2794 }
2795 break;
2796 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002797 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2798 {
2799 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002800 sendStickyBroadcast(intent);
2801 break;
2802 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002803 case EVENT_SET_POLICY_DATA_ENABLE: {
2804 final int networkType = msg.arg1;
2805 final boolean enabled = msg.arg2 == ENABLED;
2806 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002807 break;
2808 }
2809 case EVENT_VPN_STATE_CHANGED: {
2810 if (mLockdownTracker != null) {
2811 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2812 }
2813 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07002814 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002815 }
2816 }
2817 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002818
2819 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002820 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002821 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002822
2823 if (isTetheringSupported()) {
2824 return mTethering.tether(iface);
2825 } else {
2826 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2827 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002828 }
2829
2830 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002831 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002832 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002833
2834 if (isTetheringSupported()) {
2835 return mTethering.untether(iface);
2836 } else {
2837 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2838 }
2839 }
2840
2841 // javadoc from interface
2842 public int getLastTetherError(String iface) {
2843 enforceTetherAccessPermission();
2844
2845 if (isTetheringSupported()) {
2846 return mTethering.getLastTetherError(iface);
2847 } else {
2848 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2849 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002850 }
2851
2852 // TODO - proper iface API for selection by property, inspection, etc
2853 public String[] getTetherableUsbRegexs() {
2854 enforceTetherAccessPermission();
2855 if (isTetheringSupported()) {
2856 return mTethering.getTetherableUsbRegexs();
2857 } else {
2858 return new String[0];
2859 }
2860 }
2861
2862 public String[] getTetherableWifiRegexs() {
2863 enforceTetherAccessPermission();
2864 if (isTetheringSupported()) {
2865 return mTethering.getTetherableWifiRegexs();
2866 } else {
2867 return new String[0];
2868 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002869 }
2870
Danica Chang96567052010-08-11 14:54:43 -07002871 public String[] getTetherableBluetoothRegexs() {
2872 enforceTetherAccessPermission();
2873 if (isTetheringSupported()) {
2874 return mTethering.getTetherableBluetoothRegexs();
2875 } else {
2876 return new String[0];
2877 }
2878 }
2879
Mike Lockwooded4a1742011-07-19 13:04:47 -07002880 public int setUsbTethering(boolean enable) {
2881 enforceTetherAccessPermission();
2882 if (isTetheringSupported()) {
2883 return mTethering.setUsbTethering(enable);
2884 } else {
2885 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2886 }
2887 }
2888
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002889 // TODO - move iface listing, queries, etc to new module
2890 // javadoc from interface
2891 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002892 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002893 return mTethering.getTetherableIfaces();
2894 }
2895
2896 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002897 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002898 return mTethering.getTetheredIfaces();
2899 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002900
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002901 @Override
2902 public String[] getTetheredIfacePairs() {
2903 enforceTetherAccessPermission();
2904 return mTethering.getTetheredIfacePairs();
2905 }
2906
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002907 public String[] getTetheringErroredIfaces() {
2908 enforceTetherAccessPermission();
2909 return mTethering.getErroredIfaces();
2910 }
2911
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002912 // if ro.tether.denied = true we default to no tethering
2913 // gservices could set the secure setting to 1 though to enable it on a build where it
2914 // had previously been turned off.
2915 public boolean isTetheringSupported() {
2916 enforceTetherAccessPermission();
2917 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002918 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2919 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2920 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002921 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002922
2923 // An API NetworkStateTrackers can call when they lose their network.
2924 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2925 // whichever happens first. The timer is started by the first caller and not
2926 // restarted by subsequent callers.
2927 public void requestNetworkTransitionWakelock(String forWhom) {
2928 enforceConnectivityInternalPermission();
2929 synchronized (this) {
2930 if (mNetTransitionWakeLock.isHeld()) return;
2931 mNetTransitionWakeLockSerialNumber++;
2932 mNetTransitionWakeLock.acquire();
2933 mNetTransitionWakeLockCausedBy = forWhom;
2934 }
2935 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002936 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002937 mNetTransitionWakeLockSerialNumber, 0),
2938 mNetTransitionWakeLockTimeout);
2939 return;
2940 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002941
Robert Greenwalt986c7412010-09-08 15:24:47 -07002942 // 100 percent is full good, 0 is full bad.
2943 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002944 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002945 mContext.enforceCallingOrSelfPermission(
2946 android.Manifest.permission.STATUS_BAR,
2947 "ConnectivityService");
2948
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002949 if (DBG) {
2950 int pid = getCallingPid();
2951 int uid = getCallingUid();
2952 String s = pid + "(" + uid + ") reports inet is " +
2953 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2954 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2955 mInetLog.add(s);
2956 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2957 mInetLog.remove(0);
2958 }
2959 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002960 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002961 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2962 }
2963
2964 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002965 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07002966 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002967 return;
2968 }
2969 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07002970 if (DBG) log("handleInetConditionChange: net=" + netType +
2971 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002972 return;
2973 }
Wink Savillea7d56572011-09-21 11:05:43 -07002974 if (VDBG) {
2975 log("handleInetConditionChange: net=" +
2976 netType + ", condition=" + condition +
2977 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2978 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002979 mDefaultInetCondition = condition;
2980 int delay;
2981 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07002982 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002983 // setup a new hold to debounce this
2984 if (mDefaultInetCondition > 50) {
2985 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2986 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2987 } else {
2988 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2989 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2990 }
2991 mInetConditionChangeInFlight = true;
2992 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2993 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2994 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002995 // we've set the new condition, when this hold ends that will get picked up
2996 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002997 }
2998 }
2999
3000 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003001 if (DBG) {
3002 log("handleInetConditionHoldEnd: net=" + netType +
3003 ", condition=" + mDefaultInetCondition +
3004 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003005 }
3006 mInetConditionChangeInFlight = false;
3007
3008 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003009 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003010 return;
3011 }
3012 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003013 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003014 return;
3015 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07003016 // TODO: Figure out why this optimization sometimes causes a
3017 // change in mDefaultInetCondition to be missed and the
3018 // UI to not be updated.
3019 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3020 // if (DBG) log("no change in condition - aborting");
3021 // return;
3022 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003023 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3024 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003025 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003026 return;
3027 }
3028 mDefaultInetConditionPublished = mDefaultInetCondition;
3029 sendInetConditionBroadcast(networkInfo);
3030 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003031 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003032
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003033 public ProxyProperties getProxy() {
3034 synchronized (mDefaultProxyLock) {
3035 return mDefaultProxyDisabled ? null : mDefaultProxy;
3036 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003037 }
3038
3039 public void setGlobalProxy(ProxyProperties proxyProperties) {
3040 enforceChangePermission();
3041 synchronized (mGlobalProxyLock) {
3042 if (proxyProperties == mGlobalProxy) return;
3043 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3044 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3045
3046 String host = "";
3047 int port = 0;
3048 String exclList = "";
3049 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3050 mGlobalProxy = new ProxyProperties(proxyProperties);
3051 host = mGlobalProxy.getHost();
3052 port = mGlobalProxy.getPort();
3053 exclList = mGlobalProxy.getExclusionList();
3054 } else {
3055 mGlobalProxy = null;
3056 }
3057 ContentResolver res = mContext.getContentResolver();
3058 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
3059 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003060 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003061 exclList);
3062 }
3063
3064 if (mGlobalProxy == null) {
3065 proxyProperties = mDefaultProxy;
3066 }
Chia-chi Yehae166612011-09-28 16:38:18 -07003067 //sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003068 }
3069
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003070 private void loadGlobalProxy() {
3071 ContentResolver res = mContext.getContentResolver();
3072 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
3073 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
3074 String exclList = Settings.Secure.getString(res,
3075 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3076 if (!TextUtils.isEmpty(host)) {
3077 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
3078 synchronized (mGlobalProxyLock) {
3079 mGlobalProxy = proxyProperties;
3080 }
3081 }
3082 }
3083
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003084 public ProxyProperties getGlobalProxy() {
3085 synchronized (mGlobalProxyLock) {
3086 return mGlobalProxy;
3087 }
3088 }
3089
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003090 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3091 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3092 proxy = null;
3093 }
3094 synchronized (mDefaultProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003095 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3096 if (mDefaultProxy == proxy) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003097 mDefaultProxy = proxy;
3098
3099 if (!mDefaultProxyDisabled) {
3100 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003101 }
3102 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003103 }
3104
3105 private void handleDeprecatedGlobalHttpProxy() {
3106 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
3107 Settings.Secure.HTTP_PROXY);
3108 if (!TextUtils.isEmpty(proxy)) {
3109 String data[] = proxy.split(":");
3110 String proxyHost = data[0];
3111 int proxyPort = 8080;
3112 if (data.length > 1) {
3113 try {
3114 proxyPort = Integer.parseInt(data[1]);
3115 } catch (NumberFormatException e) {
3116 return;
3117 }
3118 }
3119 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3120 setGlobalProxy(p);
3121 }
3122 }
3123
3124 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003125 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07003126 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003127 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003128 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3129 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003130 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003131 final long ident = Binder.clearCallingIdentity();
3132 try {
3133 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3134 } finally {
3135 Binder.restoreCallingIdentity(ident);
3136 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003137 }
3138
3139 private static class SettingsObserver extends ContentObserver {
3140 private int mWhat;
3141 private Handler mHandler;
3142 SettingsObserver(Handler handler, int what) {
3143 super(handler);
3144 mHandler = handler;
3145 mWhat = what;
3146 }
3147
3148 void observe(Context context) {
3149 ContentResolver resolver = context.getContentResolver();
3150 resolver.registerContentObserver(Settings.Secure.getUriFor(
3151 Settings.Secure.HTTP_PROXY), false, this);
3152 }
3153
3154 @Override
3155 public void onChange(boolean selfChange) {
3156 mHandler.obtainMessage(mWhat).sendToTarget();
3157 }
3158 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003159
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003160 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003161 Slog.d(TAG, s);
3162 }
3163
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003164 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003165 Slog.e(TAG, s);
3166 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003167
repo syncf5de5572011-07-29 23:55:49 -07003168 int convertFeatureToNetworkType(int networkType, String feature) {
3169 int usedNetworkType = networkType;
3170
3171 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3172 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3173 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3174 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3175 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3176 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3177 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3178 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3179 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3180 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3181 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3182 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3183 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3184 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3185 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3186 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3187 } else {
3188 Slog.e(TAG, "Can't match any mobile netTracker!");
3189 }
3190 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3191 if (TextUtils.equals(feature, "p2p")) {
3192 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3193 } else {
3194 Slog.e(TAG, "Can't match any wifi netTracker!");
3195 }
3196 } else {
3197 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003198 }
repo syncf5de5572011-07-29 23:55:49 -07003199 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003200 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003201
3202 private static <T> T checkNotNull(T value, String message) {
3203 if (value == null) {
3204 throw new NullPointerException(message);
3205 }
3206 return value;
3207 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003208
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003209 /**
3210 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003211 * VpnBuilder and not available in ConnectivityManager. Permissions
3212 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003213 * @hide
3214 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003215 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003216 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003217 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003218 try {
3219 int type = mActiveDefaultNetwork;
3220 if (ConnectivityManager.isNetworkTypeValid(type)) {
3221 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3222 return true;
3223 }
3224 } catch (Exception e) {
3225 // ignore
3226 } finally {
3227 try {
3228 socket.close();
3229 } catch (Exception e) {
3230 // ignore
3231 }
3232 }
3233 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003234 }
3235
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003236 /**
3237 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003238 * and not available in ConnectivityManager. Permissions are checked
3239 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003240 * @hide
3241 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003242 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003243 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003244 throwIfLockdownEnabled();
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003245 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003246 }
3247
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003248 /**
3249 * Configure a TUN interface and return its file descriptor. Parameters
3250 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003251 * and not available in ConnectivityManager. Permissions are checked in
3252 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003253 * @hide
3254 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003255 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003256 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003257 throwIfLockdownEnabled();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003258 return mVpn.establish(config);
3259 }
3260
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003261 /**
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003262 * Start legacy VPN, controlling native daemons as needed. Creates a
3263 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003264 */
3265 @Override
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003266 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003267 throwIfLockdownEnabled();
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003268 final LinkProperties egress = getActiveLinkProperties();
3269 if (egress == null) {
3270 throw new IllegalStateException("Missing active network connection");
3271 }
3272 mVpn.startLegacyVpn(profile, mKeyStore, egress);
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003273 }
3274
3275 /**
3276 * Return the information of the ongoing legacy VPN. This method is used
3277 * by VpnSettings and not available in ConnectivityManager. Permissions
3278 * are checked in Vpn class.
3279 * @hide
3280 */
3281 @Override
3282 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003283 throwIfLockdownEnabled();
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003284 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003285 }
3286
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003287 /**
3288 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3289 * through NetworkStateTracker since it works differently. For example, it
3290 * needs to override DNS servers but never takes the default routes. It
3291 * relies on another data network, and it could keep existing connections
3292 * alive after reconnecting, switching between networks, or even resuming
3293 * from deep sleep. Calls from applications should be done synchronously
3294 * to avoid race conditions. As these are all hidden APIs, refactoring can
3295 * be done whenever a better abstraction is developed.
3296 */
3297 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003298 private VpnCallback() {
3299 }
3300
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003301 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003302 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003303 }
3304
Chia-chi Yehcc844502011-07-14 18:01:57 -07003305 public void override(List<String> dnsServers, List<String> searchDomains) {
3306 if (dnsServers == null) {
3307 restore();
3308 return;
3309 }
3310
3311 // Convert DNS servers into addresses.
3312 List<InetAddress> addresses = new ArrayList<InetAddress>();
3313 for (String address : dnsServers) {
3314 // Double check the addresses and remove invalid ones.
3315 try {
3316 addresses.add(InetAddress.parseNumericAddress(address));
3317 } catch (Exception e) {
3318 // ignore
3319 }
3320 }
3321 if (addresses.isEmpty()) {
3322 restore();
3323 return;
3324 }
3325
3326 // Concatenate search domains into a string.
3327 StringBuilder buffer = new StringBuilder();
3328 if (searchDomains != null) {
3329 for (String domain : searchDomains) {
3330 buffer.append(domain).append(' ');
3331 }
3332 }
3333 String domains = buffer.toString().trim();
3334
3335 // Apply DNS changes.
3336 boolean changed = false;
3337 synchronized (mDnsLock) {
Lorenzo Colittiaa035382011-09-28 22:31:45 -07003338 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003339 mDnsOverridden = true;
3340 }
3341 if (changed) {
3342 bumpDns();
3343 }
3344
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003345 // Temporarily disable the default proxy.
3346 synchronized (mDefaultProxyLock) {
3347 mDefaultProxyDisabled = true;
3348 if (mDefaultProxy != null) {
3349 sendProxyBroadcast(null);
3350 }
3351 }
3352
3353 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003354 }
3355
Chia-chi Yehcc844502011-07-14 18:01:57 -07003356 public void restore() {
3357 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003358 if (mDnsOverridden) {
3359 mDnsOverridden = false;
3360 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003361 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003362 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003363 synchronized (mDefaultProxyLock) {
3364 mDefaultProxyDisabled = false;
3365 if (mDefaultProxy != null) {
3366 sendProxyBroadcast(mDefaultProxy);
3367 }
3368 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003369 }
3370 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003371
3372 @Override
3373 public boolean updateLockdownVpn() {
Jeff Sharkey69fc5f82012-09-06 17:54:29 -07003374 enforceSystemUid();
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003375
3376 // Tear down existing lockdown if profile was removed
3377 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3378 if (mLockdownEnabled) {
3379 if (mKeyStore.state() != KeyStore.State.UNLOCKED) {
3380 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3381 return false;
3382 }
3383
3384 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3385 final VpnProfile profile = VpnProfile.decode(
3386 profileName, mKeyStore.get(Credentials.VPN + profileName));
3387 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3388 } else {
3389 setLockdownTracker(null);
3390 }
3391
3392 return true;
3393 }
3394
3395 /**
3396 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3397 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3398 */
3399 private void setLockdownTracker(LockdownVpnTracker tracker) {
3400 // Shutdown any existing tracker
3401 final LockdownVpnTracker existing = mLockdownTracker;
3402 mLockdownTracker = null;
3403 if (existing != null) {
3404 existing.shutdown();
3405 }
3406
3407 try {
3408 if (tracker != null) {
3409 mNetd.setFirewallEnabled(true);
3410 mLockdownTracker = tracker;
3411 mLockdownTracker.init();
3412 } else {
3413 mNetd.setFirewallEnabled(false);
3414 }
3415 } catch (RemoteException e) {
3416 // ignored; NMS lives inside system_server
3417 }
3418 }
3419
3420 private void throwIfLockdownEnabled() {
3421 if (mLockdownEnabled) {
3422 throw new IllegalStateException("Unavailable in lockdown mode");
3423 }
3424 }
Jeff Sharkey69fc5f82012-09-06 17:54:29 -07003425
3426 private static void enforceSystemUid() {
3427 final int uid = Binder.getCallingUid();
3428 if (uid != Process.SYSTEM_UID) {
3429 throw new SecurityException("Only available to AID_SYSTEM");
3430 }
3431 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003432}