blob: c7903c0e93a34e4ea600c278cf6ba0bb67ea32fc [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070020import static android.net.ConnectivityManager.isNetworkTypeValid;
21import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070022import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070023
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080024import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080025import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070029import android.database.ContentObserver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080030import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080031import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080032import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080033import android.net.IConnectivityManager;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070034import android.net.INetworkPolicyListener;
35import android.net.INetworkPolicyManager;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070036import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080037import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070038import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080039import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070040import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080041import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070042import android.net.NetworkInfo.DetailedState;
Jeff Sharkey21062e72011-05-28 20:56:34 -070043import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080044import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070045import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070046import android.net.Proxy;
47import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070048import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080049import android.net.wifi.WifiStateTracker;
50import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040051import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080052import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070053import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070054import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070055import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080056import android.os.Looper;
57import android.os.Message;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070058import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070059import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070060import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080061import android.os.ServiceManager;
62import android.os.SystemProperties;
63import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070064import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080066import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070067import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080068
Chia-chi Yehbded3eb2011-07-04 03:23:12 -070069import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -070070import com.android.internal.net.VpnConfig;
Robert Greenwalt2034b912009-08-12 16:08:25 -070071import com.android.internal.telephony.Phone;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080072import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070073import com.android.server.connectivity.Vpn;
74
Jeff Sharkey21062e72011-05-28 20:56:34 -070075import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070076import com.google.android.collect.Sets;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080077
The Android Open Source Project28527d22009-03-03 19:31:44 -080078import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070079import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080080import java.io.PrintWriter;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070081import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -070082import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070083import java.net.InetAddress;
84import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -070085import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070086import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070087import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -070088import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070089import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -070090import java.util.List;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070091import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project28527d22009-03-03 19:31:44 -080092
93/**
94 * @hide
95 */
96public class ConnectivityService extends IConnectivityManager.Stub {
97
Robert Greenwalt063dc7d2010-10-05 19:12:26 -070098 private static final boolean DBG = true;
Wink Saville051a6642011-07-13 13:44:13 -070099 private static final boolean VDBG = true;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800100 private static final String TAG = "ConnectivityService";
101
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700102 private static final boolean LOGD_RULES = false;
103
Robert Greenwalt2034b912009-08-12 16:08:25 -0700104 // how long to wait before switching back to a radio's default network
105 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
106 // system property that can override the above value
107 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
108 "android.telephony.apn-restore";
109
Robert Greenwaltbd492212011-05-06 17:10:53 -0700110 // used in recursive route setting to add gateways for the host for which
111 // a host route was requested.
112 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
113
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800114 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800115 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800116
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700117 private Vpn mVpn;
118
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700119 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
120 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700121 /** Currently active network rules by UID. */
122 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700123 /** Set of ifaces that are costly. */
124 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700125
The Android Open Source Project28527d22009-03-03 19:31:44 -0800126 /**
127 * Sometimes we want to refer to the individual network state
128 * trackers separately, and sometimes we just want to treat them
129 * abstractly.
130 */
131 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700132
133 /**
Wink Saville051a6642011-07-13 13:44:13 -0700134 * The link properties that define the current links
135 */
136 private LinkProperties mCurrentLinkProperties[];
137
138 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700139 * A per Net list of the PID's that requested access to the net
140 * used both as a refcount and for per-PID DNS selection
141 */
142 private List mNetRequestersPids[];
143
Robert Greenwalt2034b912009-08-12 16:08:25 -0700144 // priority order of the nettrackers
145 // (excluding dynamically set mNetworkPreference)
146 // TODO - move mNetworkTypePreference into this
147 private int[] mPriorityList;
148
The Android Open Source Project28527d22009-03-03 19:31:44 -0800149 private Context mContext;
150 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700151 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700152 // 0 is full bad, 100 is full good
153 private int mDefaultInetCondition = 0;
154 private int mDefaultInetConditionPublished = 0;
155 private boolean mInetConditionChangeInFlight = false;
156 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800157
158 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800159
160 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700161 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800162
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800163 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
164
Robert Greenwalt355205c2011-05-10 15:05:02 -0700165 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700166 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700167
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700168 private static final int ENABLED = 1;
169 private static final int DISABLED = 0;
170
171 // Share the event space with NetworkStateTracker (which can't see this
172 // internal class but sends us events). If you change these, change
173 // NetworkStateTracker.java too.
174 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
175 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
176
177 /**
178 * used internally as a delayed event to make us switch back to the
179 * default network
180 */
181 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
182 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
183
184 /**
185 * used internally to change our mobile data enabled flag
186 */
187 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
188 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
189
190 /**
191 * used internally to change our network preference setting
192 * arg1 = networkType to prefer
193 */
194 private static final int EVENT_SET_NETWORK_PREFERENCE =
195 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
196
197 /**
198 * used internally to synchronize inet condition reports
199 * arg1 = networkType
200 * arg2 = condition (0 bad, 100 good)
201 */
202 private static final int EVENT_INET_CONDITION_CHANGE =
203 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
204
205 /**
206 * used internally to mark the end of inet condition hold periods
207 * arg1 = networkType
208 */
209 private static final int EVENT_INET_CONDITION_HOLD_END =
210 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
211
212 /**
213 * used internally to set the background data preference
214 * arg1 = TRUE for enabled, FALSE for disabled
215 */
216 private static final int EVENT_SET_BACKGROUND_DATA =
217 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
218
219 /**
220 * used internally to set enable/disable cellular data
221 * arg1 = ENBALED or DISABLED
222 */
223 private static final int EVENT_SET_MOBILE_DATA =
224 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
225
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700226 /**
227 * used internally to clear a wakelock when transitioning
228 * from one net to another
229 */
230 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
231 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
232
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700233 /**
234 * used internally to reload global proxy settings
235 */
236 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
237 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
238
Robert Greenwalt34848c02011-03-25 13:09:25 -0700239 /**
240 * used internally to set external dependency met/unmet
241 * arg1 = ENABLED (met) or DISABLED (unmet)
242 * arg2 = NetworkType
243 */
244 private static final int EVENT_SET_DEPENDENCY_MET =
245 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
246
Robert Greenwalt2034b912009-08-12 16:08:25 -0700247 private Handler mHandler;
248
249 // list of DeathRecipients used to make sure features are turned off when
250 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500251 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700252
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400253 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800254 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400255
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700256 private PowerManager.WakeLock mNetTransitionWakeLock;
257 private String mNetTransitionWakeLockCausedBy = "";
258 private int mNetTransitionWakeLockSerialNumber;
259 private int mNetTransitionWakeLockTimeout;
260
Robert Greenwalt94daa182010-09-01 11:34:05 -0700261 private InetAddress mDefaultDns;
262
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700263 // this collection is used to refcount the added routes - if there are none left
264 // it's time to remove the route from the route table
265 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
266
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700267 // used in DBG mode to track inet condition reports
268 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
269 private ArrayList mInetLog;
270
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700271 // track the current default http proxy - tell the world if we get a new one (real change)
272 private ProxyProperties mDefaultProxy = null;
273 // track the global proxy.
274 private ProxyProperties mGlobalProxy = null;
275 private final Object mGlobalProxyLock = new Object();
276
277 private SettingsObserver mSettingsObserver;
278
Robert Greenwalt34848c02011-03-25 13:09:25 -0700279 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700280 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700281
Robert Greenwalt12c44552009-12-07 11:33:18 -0800282 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700283 public int mSimultaneity;
284 public int mType;
285 public RadioAttributes(String init) {
286 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700287 mType = Integer.parseInt(fragments[0]);
288 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700289 }
290 }
291 RadioAttributes[] mRadioAttributes;
292
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700293 // the set of network types that can only be enabled by system/sig apps
294 List mProtectedNetworks;
295
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700296 public ConnectivityService(
297 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800298 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800299
Wink Saville775aad62010-09-02 19:23:52 -0700300 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
301 handlerThread.start();
302 mHandler = new MyHandler(handlerThread.getLooper());
303
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800304 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
305 Settings.Secure.BACKGROUND_DATA, 1) == 1);
306
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800307 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800308 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
309 String id = Settings.Secure.getString(context.getContentResolver(),
310 Settings.Secure.ANDROID_ID);
311 if (id != null && id.length() > 0) {
312 String name = new String("android_").concat(id);
313 SystemProperties.set("net.hostname", name);
314 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800315 }
316
Robert Greenwalt94daa182010-09-01 11:34:05 -0700317 // read our default dns server ip
318 String dns = Settings.Secure.getString(context.getContentResolver(),
319 Settings.Secure.DEFAULT_DNS_SERVER);
320 if (dns == null || dns.length() == 0) {
321 dns = context.getResources().getString(
322 com.android.internal.R.string.config_default_dns_server);
323 }
324 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800325 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
326 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800327 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700328 }
329
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700330 mContext = checkNotNull(context, "missing Context");
331 mNetd = checkNotNull(netd, "missing INetworkManagementService");
332 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700333
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700334 try {
335 mPolicyManager.registerListener(mPolicyListener);
336 } catch (RemoteException e) {
337 // ouch, no rules updates means some processes may never get network
338 Slog.e(TAG, "unable to register INetworkPolicyListener", e);
339 }
340
341 final PowerManager powerManager = (PowerManager) context.getSystemService(
342 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700343 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
344 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
345 com.android.internal.R.integer.config_networkTransitionTimeout);
346
Robert Greenwalt2034b912009-08-12 16:08:25 -0700347 mNetTrackers = new NetworkStateTracker[
348 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700349 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700350
The Android Open Source Project28527d22009-03-03 19:31:44 -0800351 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700352
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700353 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700354 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700355
Robert Greenwalt2034b912009-08-12 16:08:25 -0700356 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700357 String[] raStrings = context.getResources().getStringArray(
358 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700359 for (String raString : raStrings) {
360 RadioAttributes r = new RadioAttributes(raString);
361 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800362 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700363 continue;
364 }
365 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800366 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700367 r.mType);
368 continue;
369 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700370 mRadioAttributes[r.mType] = r;
371 }
372
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700373 String[] naStrings = context.getResources().getStringArray(
374 com.android.internal.R.array.networkAttributes);
375 for (String naString : naStrings) {
376 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700377 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700378 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800379 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700380 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700381 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700382 }
Wink Savillef2a62832011-04-07 14:23:45 -0700383 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800384 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700385 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700386 continue;
387 }
Wink Savillef2a62832011-04-07 14:23:45 -0700388 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800389 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700390 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700391 continue;
392 }
Wink Savillef2a62832011-04-07 14:23:45 -0700393 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700394 mNetworksDefined++;
395 } catch(Exception e) {
396 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700397 }
398 }
399
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700400 mProtectedNetworks = new ArrayList<Integer>();
401 int[] protectedNetworks = context.getResources().getIntArray(
402 com.android.internal.R.array.config_protectedNetworks);
403 for (int p : protectedNetworks) {
404 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
405 mProtectedNetworks.add(p);
406 } else {
407 if (DBG) loge("Ignoring protectedNetwork " + p);
408 }
409 }
410
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700411 // high priority first
412 mPriorityList = new int[mNetworksDefined];
413 {
414 int insertionPoint = mNetworksDefined-1;
415 int currentLowest = 0;
416 int nextLowest = 0;
417 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700418 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700419 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700420 if (na.priority < currentLowest) continue;
421 if (na.priority > currentLowest) {
422 if (na.priority < nextLowest || nextLowest == 0) {
423 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700424 }
425 continue;
426 }
Wink Savillef2a62832011-04-07 14:23:45 -0700427 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700428 }
429 currentLowest = nextLowest;
430 nextLowest = 0;
431 }
432 }
433
434 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
435 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700436 mNetRequestersPids[i] = new ArrayList();
437 }
438
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500439 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700440
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700441 mNumDnsEntries = 0;
442
443 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
444 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800445 /*
446 * Create the network state trackers for Wi-Fi and mobile
447 * data. Maybe this could be done with a factory class,
448 * but it's not clear that it's worth it, given that
449 * the number of different network types is not going
450 * to change very often.
451 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700452 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700453 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700454 case ConnectivityManager.TYPE_WIFI:
Wink Savillee70c6f52010-12-03 12:01:38 -0800455 if (DBG) log("Starting Wifi Service.");
Wink Saville7fabfa22010-08-13 16:11:42 -0700456 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff25be0762010-07-28 09:35:20 -0700457 WifiService wifiService = new WifiService(context);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700458 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff25be0762010-07-28 09:35:20 -0700459 wifiService.checkAndStartWifi();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700460 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Saville7fabfa22010-08-13 16:11:42 -0700461 wst.startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700462 break;
463 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700464 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700465 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700466 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700467 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800468 case ConnectivityManager.TYPE_DUMMY:
469 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700470 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800471 mNetTrackers[netType].startMonitoring(context, mHandler);
472 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800473 case ConnectivityManager.TYPE_BLUETOOTH:
474 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
475 mNetTrackers[netType].startMonitoring(context, mHandler);
476 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800477 case ConnectivityManager.TYPE_ETHERNET:
478 mNetTrackers[netType] = EthernetDataTracker.getInstance();
479 mNetTrackers[netType].startMonitoring(context, mHandler);
480 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700481 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800482 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700483 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700484 continue;
485 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700486 mCurrentLinkProperties[netType] = null;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700487 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800488
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700489 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
490 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
491
492 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700493 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700494 mTethering.getTetherableWifiRegexs().length != 0 ||
495 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700496 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800497
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700498 mVpn = new Vpn(mContext, new VpnCallback());
499
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700500 try {
501 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700502 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700503 } catch (RemoteException e) {
504 loge("Error registering observer :" + e);
505 }
506
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700507 if (DBG) {
508 mInetLog = new ArrayList();
509 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700510
511 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
512 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800513
514 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800515 }
516
517 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700518 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800519 * @param preference the new preference
520 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700521 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800522 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700523
524 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800525 }
526
527 public int getNetworkPreference() {
528 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700529 int preference;
530 synchronized(this) {
531 preference = mNetworkPreference;
532 }
533 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800534 }
535
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700536 private void handleSetNetworkPreference(int preference) {
537 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700538 mNetConfigs[preference] != null &&
539 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700540 if (mNetworkPreference != preference) {
541 final ContentResolver cr = mContext.getContentResolver();
542 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
543 synchronized(this) {
544 mNetworkPreference = preference;
545 }
546 enforcePreference();
547 }
548 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800549 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700550
The Android Open Source Project28527d22009-03-03 19:31:44 -0800551 private int getPersistedNetworkPreference() {
552 final ContentResolver cr = mContext.getContentResolver();
553
554 final int networkPrefSetting = Settings.Secure
555 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
556 if (networkPrefSetting != -1) {
557 return networkPrefSetting;
558 }
559
560 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
561 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700562
The Android Open Source Project28527d22009-03-03 19:31:44 -0800563 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700564 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800565 * In this method, we only tear down a non-preferred network. Establishing
566 * a connection to the preferred network is taken care of when we handle
567 * the disconnect event from the non-preferred network
568 * (see {@link #handleDisconnect(NetworkInfo)}).
569 */
570 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700571 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800572 return;
573
Robert Greenwalt2034b912009-08-12 16:08:25 -0700574 if (!mNetTrackers[mNetworkPreference].isAvailable())
575 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800576
Robert Greenwalt2034b912009-08-12 16:08:25 -0700577 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700578 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700579 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700580 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800581 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700582 " in enforcePreference");
583 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700584 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800585 }
586 }
587 }
588
589 private boolean teardown(NetworkStateTracker netTracker) {
590 if (netTracker.teardown()) {
591 netTracker.setTeardownRequested(true);
592 return true;
593 } else {
594 return false;
595 }
596 }
597
598 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700599 * Check if UID should be blocked from using the network represented by the
600 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700601 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700602 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
603 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700604
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700605 final boolean networkCostly;
606 final int uidRules;
607 synchronized (mRulesLock) {
608 networkCostly = mMeteredIfaces.contains(iface);
609 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700610 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700611
612 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
613 return true;
614 }
615
616 // no restrictive rules; network is visible
617 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700618 }
619
620 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700621 * Return a filtered {@link NetworkInfo}, potentially marked
622 * {@link DetailedState#BLOCKED} based on
623 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700624 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700625 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
626 NetworkInfo info = tracker.getNetworkInfo();
627 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700628 // network is blocked; clone and override state
629 info = new NetworkInfo(info);
630 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700631 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700632 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700633 }
634
635 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800636 * Return NetworkInfo for the active (i.e., connected) network interface.
637 * It is assumed that at most one network is active at a time. If more
638 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700639 * @return the info for the active network, or {@code null} if none is
640 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800641 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700642 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800643 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700644 enforceAccessPermission();
645 final int uid = Binder.getCallingUid();
646 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800647 }
648
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700649 @Override
650 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
651 enforceConnectivityInternalPermission();
652 return getNetworkInfo(mActiveDefaultNetwork, uid);
653 }
654
655 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800656 public NetworkInfo getNetworkInfo(int networkType) {
657 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700658 final int uid = Binder.getCallingUid();
659 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800660 }
661
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700662 private NetworkInfo getNetworkInfo(int networkType, int uid) {
663 NetworkInfo info = null;
664 if (isNetworkTypeValid(networkType)) {
665 final NetworkStateTracker tracker = mNetTrackers[networkType];
666 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700667 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700668 }
669 }
670 return info;
671 }
672
673 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800674 public NetworkInfo[] getAllNetworkInfo() {
675 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700676 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700677 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700678 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700679 for (NetworkStateTracker tracker : mNetTrackers) {
680 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700681 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700682 }
683 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800684 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700685 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800686 }
687
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700688 /**
689 * Return LinkProperties for the active (i.e., connected) default
690 * network interface. It is assumed that at most one default network
691 * is active at a time. If more than one is active, it is indeterminate
692 * which will be returned.
693 * @return the ip properties for the active network, or {@code null} if
694 * none is active
695 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700696 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700697 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700698 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700699 }
700
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700701 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700702 public LinkProperties getLinkProperties(int networkType) {
703 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700704 if (isNetworkTypeValid(networkType)) {
705 final NetworkStateTracker tracker = mNetTrackers[networkType];
706 if (tracker != null) {
707 return tracker.getLinkProperties();
708 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700709 }
710 return null;
711 }
712
Jeff Sharkey21062e72011-05-28 20:56:34 -0700713 @Override
714 public NetworkState[] getAllNetworkState() {
715 enforceAccessPermission();
716 final int uid = Binder.getCallingUid();
717 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700718 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700719 for (NetworkStateTracker tracker : mNetTrackers) {
720 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700721 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700722 result.add(new NetworkState(
723 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
724 }
725 }
726 }
727 return result.toArray(new NetworkState[result.size()]);
728 }
729
The Android Open Source Project28527d22009-03-03 19:31:44 -0800730 public boolean setRadios(boolean turnOn) {
731 boolean result = true;
732 enforceChangePermission();
733 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700734 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800735 }
736 return result;
737 }
738
739 public boolean setRadio(int netType, boolean turnOn) {
740 enforceChangePermission();
741 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
742 return false;
743 }
744 NetworkStateTracker tracker = mNetTrackers[netType];
745 return tracker != null && tracker.setRadio(turnOn);
746 }
747
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700748 /**
749 * Used to notice when the calling process dies so we can self-expire
750 *
751 * Also used to know if the process has cleaned up after itself when
752 * our auto-expire timer goes off. The timer has a link to an object.
753 *
754 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700755 private class FeatureUser implements IBinder.DeathRecipient {
756 int mNetworkType;
757 String mFeature;
758 IBinder mBinder;
759 int mPid;
760 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800761 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700762
763 FeatureUser(int type, String feature, IBinder binder) {
764 super();
765 mNetworkType = type;
766 mFeature = feature;
767 mBinder = binder;
768 mPid = getCallingPid();
769 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800770 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700771
Robert Greenwalt2034b912009-08-12 16:08:25 -0700772 try {
773 mBinder.linkToDeath(this, 0);
774 } catch (RemoteException e) {
775 binderDied();
776 }
777 }
778
779 void unlinkDeathRecipient() {
780 mBinder.unlinkToDeath(this, 0);
781 }
782
783 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800784 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800785 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
786 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700787 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700788 }
789
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700790 public void expire() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800791 log("ConnectivityService FeatureUser expire(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800792 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
793 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700794 stopUsingNetworkFeature(this, false);
795 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800796
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500797 public boolean isSameUser(FeatureUser u) {
798 if (u == null) return false;
799
800 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
801 }
802
803 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
804 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
805 TextUtils.equals(mFeature, feature)) {
806 return true;
807 }
808 return false;
809 }
810
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800811 public String toString() {
812 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
813 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
814 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700815 }
816
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700817 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700818 public int startUsingNetworkFeature(int networkType, String feature,
819 IBinder binder) {
820 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800821 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700822 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800823 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700824 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700825 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700826 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800827 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700828
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700829 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700830
831 // TODO - move this into the MobileDataStateTracker
832 int usedNetworkType = networkType;
833 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800834 usedNetworkType = convertFeatureToNetworkType(feature);
835 if (usedNetworkType < 0) {
836 Slog.e(TAG, "Can't match any netTracker!");
837 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700838 }
839 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700840
841 if (mProtectedNetworks.contains(usedNetworkType)) {
842 enforceConnectivityInternalPermission();
843 }
844
Robert Greenwalt2034b912009-08-12 16:08:25 -0700845 NetworkStateTracker network = mNetTrackers[usedNetworkType];
846 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800847 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700848 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700849 NetworkStateTracker radio = mNetTrackers[networkType];
850 NetworkInfo ni = network.getNetworkInfo();
851
852 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800853 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800854 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
855 return Phone.APN_TYPE_NOT_AVAILABLE;
856 } else {
857 // else make the attempt anyway - probably giving REQUEST_STARTED below
858 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700859 }
860
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500861 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
862
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700863 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500864 boolean addToList = true;
865 if (restoreTimer < 0) {
866 // In case there is no timer is specified for the feature,
867 // make sure we don't add duplicate entry with the same request.
868 for (FeatureUser u : mFeatureUsers) {
869 if (u.isSameUser(f)) {
870 // Duplicate user is found. Do not add.
871 addToList = false;
872 break;
873 }
874 }
875 }
876
877 if (addToList) mFeatureUsers.add(f);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700878 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
879 // this gets used for per-pid dns when connected
880 mNetRequestersPids[usedNetworkType].add(currentPid);
881 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700882 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700883
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700884 if (restoreTimer >= 0) {
885 mHandler.sendMessageDelayed(
886 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
887 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700888
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700889 if ((ni.isConnectedOrConnecting() == true) &&
890 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700891 if (ni.isConnected() == true) {
892 // add the pid-specific dns
Robert Greenwalt3afbead2010-07-23 15:46:26 -0700893 handleDnsConfigurationChange(networkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800894 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700895 return Phone.APN_ALREADY_ACTIVE;
896 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800897 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700898 return Phone.APN_REQUEST_STARTED;
899 }
900
901 // check if the radio in play can make another contact
902 // assume if cannot for now
903
Wink Savillee70c6f52010-12-03 12:01:38 -0800904 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700905 network.reconnect();
906 return Phone.APN_REQUEST_STARTED;
907 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800908 // need to remember this unsupported request so we respond appropriately on stop
909 synchronized(this) {
910 mFeatureUsers.add(f);
911 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
912 // this gets used for per-pid dns when connected
913 mNetRequestersPids[usedNetworkType].add(currentPid);
914 }
915 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700916 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700917 }
918 }
919 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800920 }
921
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700922 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800923 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700924 enforceChangePermission();
925
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700926 int pid = getCallingPid();
927 int uid = getCallingUid();
928
929 FeatureUser u = null;
930 boolean found = false;
931
932 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500933 for (FeatureUser x : mFeatureUsers) {
934 if (x.isSameUser(pid, uid, networkType, feature)) {
935 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700936 found = true;
937 break;
938 }
939 }
940 }
941 if (found && u != null) {
942 // stop regardless of how many other time this proc had called start
943 return stopUsingNetworkFeature(u, true);
944 } else {
945 // none found!
Wink Savillee70c6f52010-12-03 12:01:38 -0800946 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700947 return 1;
948 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700949 }
950
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700951 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
952 int networkType = u.mNetworkType;
953 String feature = u.mFeature;
954 int pid = u.mPid;
955 int uid = u.mUid;
956
957 NetworkStateTracker tracker = null;
958 boolean callTeardown = false; // used to carry our decision outside of sync block
959
Robert Greenwalt2034b912009-08-12 16:08:25 -0700960 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800961 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700962 ": " + feature);
963 }
Robert Greenwalt28f43012009-10-06 17:52:40 -0700964
The Android Open Source Project28527d22009-03-03 19:31:44 -0800965 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
966 return -1;
967 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700968
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700969 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
970 // sync block
971 synchronized(this) {
972 // check if this process still has an outstanding start request
973 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800974 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700975 return 1;
976 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700977 u.unlinkDeathRecipient();
978 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
979 // If we care about duplicate requests, check for that here.
980 //
981 // This is done to support the extension of a request - the app
982 // can request we start the network feature again and renew the
983 // auto-shutoff delay. Normal "stop" calls from the app though
984 // do not pay attention to duplicate requests - in effect the
985 // API does not refcount and a single stop will counter multiple starts.
986 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500987 for (FeatureUser x : mFeatureUsers) {
988 if (x.isSameUser(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800989 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700990 return 1;
991 }
992 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700993 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700994
995 // TODO - move to MobileDataStateTracker
996 int usedNetworkType = networkType;
997 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800998 usedNetworkType = convertFeatureToNetworkType(feature);
999 if (usedNetworkType < 0) {
1000 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001001 }
1002 }
1003 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001004 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001005 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001006 return -1;
1007 }
1008 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001009 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001010 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -08001011 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001012 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001013 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001014 "others still using it");
1015 return 1;
1016 }
1017 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001018 } else {
1019 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001020 }
1021 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001022 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001023 if (callTeardown) {
1024 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001025 return 1;
1026 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001027 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001028 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001029 }
1030
1031 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001032 * @deprecated use requestRouteToHostAddress instead
1033 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001034 * Ensure that a network route exists to deliver traffic to the specified
1035 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001036 * @param networkType the type of the network over which traffic to the
1037 * specified host is to be routed
1038 * @param hostAddress the IP address of the host to which the route is
1039 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001040 * @return {@code true} on success, {@code false} on failure
1041 */
1042 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001043 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1044
1045 if (inetAddress == null) {
1046 return false;
1047 }
1048
1049 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1050 }
1051
1052 /**
1053 * Ensure that a network route exists to deliver traffic to the specified
1054 * host via the specified network interface.
1055 * @param networkType the type of the network over which traffic to the
1056 * specified host is to be routed
1057 * @param hostAddress the IP address of the host to which the route is
1058 * desired
1059 * @return {@code true} on success, {@code false} on failure
1060 */
1061 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001062 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001063 if (mProtectedNetworks.contains(networkType)) {
1064 enforceConnectivityInternalPermission();
1065 }
1066
The Android Open Source Project28527d22009-03-03 19:31:44 -08001067 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1068 return false;
1069 }
1070 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001071
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001072 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1073 tracker.isTeardownRequested()) {
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001074 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001075 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001076 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001077 }
1078 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001079 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001080 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001081 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001082 LinkProperties lp = tracker.getLinkProperties();
1083 return addRoute(lp, RouteInfo.makeHostRoute(addr));
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001084 } catch (UnknownHostException e) {}
1085 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001086 }
1087
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001088 private boolean addRoute(LinkProperties p, RouteInfo r) {
1089 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001090 }
1091
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001092 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1093 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1094 }
1095
1096 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1097 boolean doAdd) {
1098 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1099
1100 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1101 loge("Error adding route - too much recursion");
1102 return false;
1103 }
1104
1105 if (r.isHostRoute() == false) {
1106 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1107 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001108 if (bestRoute.getGateway().equals(r.getGateway())) {
1109 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001110 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001111 } else {
1112 // if we will connect to our gateway through another route, add a direct
1113 // route to it's gateway
1114 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001115 }
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001116 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001117 }
1118 }
1119 if (doAdd) {
1120 if (DBG) log("Adding " + r + " for interface " + ifaceName);
1121 mAddedRoutes.add(r);
1122 try {
1123 mNetd.addRoute(ifaceName, r);
1124 } catch (Exception e) {
1125 // never crash - catch them all
1126 loge("Exception trying to add a route: " + e);
1127 return false;
1128 }
1129 } else {
1130 // if we remove this one and there are no more like it, then refcount==0 and
1131 // we can remove it from the table
1132 mAddedRoutes.remove(r);
1133 if (mAddedRoutes.contains(r) == false) {
1134 if (DBG) log("Removing " + r + " for interface " + ifaceName);
1135 try {
1136 mNetd.removeRoute(ifaceName, r);
1137 } catch (Exception e) {
1138 // never crash - catch them all
1139 loge("Exception trying to remove a route: " + e);
1140 return false;
1141 }
1142 } else {
1143 if (DBG) log("not removing " + r + " as it's still in use");
1144 }
1145 }
1146 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001147 }
1148
1149 /**
1150 * @see ConnectivityManager#getBackgroundDataSetting()
1151 */
1152 public boolean getBackgroundDataSetting() {
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001153 return mBackgroundDataEnabled.get();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001154 }
Robert Greenwalt0659da32009-07-16 17:21:39 -07001155
The Android Open Source Project28527d22009-03-03 19:31:44 -08001156 /**
1157 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1158 */
1159 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1160 mContext.enforceCallingOrSelfPermission(
1161 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1162 "ConnectivityService");
Robert Greenwalt0659da32009-07-16 17:21:39 -07001163
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001164 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1165
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001166 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1167 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1168 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001169
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001170 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwalt0ffdef12011-02-25 13:44:09 -08001171 Settings.Secure.putInt(mContext.getContentResolver(),
1172 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1173 Intent broadcast = new Intent(
1174 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1175 mContext.sendBroadcast(broadcast);
Robert Greenwalt0659da32009-07-16 17:21:39 -07001176 }
1177
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001178 /**
1179 * @see ConnectivityManager#getMobileDataEnabled()
1180 */
1181 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001182 // TODO: This detail should probably be in DataConnectionTracker's
1183 // which is where we store the value and maybe make this
1184 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001185 enforceAccessPermission();
1186 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1187 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savillee70c6f52010-12-03 12:01:38 -08001188 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001189 return retVal;
1190 }
1191
Robert Greenwalt34848c02011-03-25 13:09:25 -07001192 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001193 enforceConnectivityInternalPermission();
1194
Robert Greenwalt34848c02011-03-25 13:09:25 -07001195 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1196 (met ? ENABLED : DISABLED), networkType));
1197 }
1198
1199 private void handleSetDependencyMet(int networkType, boolean met) {
1200 if (mNetTrackers[networkType] != null) {
1201 if (DBG) {
1202 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1203 }
1204 mNetTrackers[networkType].setDependencyMet(met);
1205 }
1206 }
1207
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001208 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1209 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001210 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001211 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001212 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001213
1214 if (LOGD_RULES) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001215 Slog.d(TAG, "onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001216 }
1217
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001218 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001219 // skip update when we've already applied rules
1220 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1221 if (oldRules == uidRules) return;
1222
1223 mUidRules.put(uid, uidRules);
1224 }
1225
1226 // TODO: dispatch into NMS to push rules towards kernel module
1227 // TODO: notify UID when it has requested targeted updates
1228 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001229
1230 @Override
1231 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1232 // only someone like NPMS should only be calling us
1233 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1234
1235 if (LOGD_RULES) {
1236 Slog.d(TAG,
1237 "onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1238 }
1239
1240 synchronized (mRulesLock) {
1241 mMeteredIfaces.clear();
1242 for (String iface : meteredIfaces) {
1243 mMeteredIfaces.add(iface);
1244 }
1245 }
1246 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001247 };
1248
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001249 /**
1250 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1251 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001252 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001253 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001254 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001255
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001256 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001257 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001258 }
1259
1260 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001261 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1262 if (DBG) {
1263 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001264 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001265 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001266 }
1267 }
1268
The Android Open Source Project28527d22009-03-03 19:31:44 -08001269 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001270 mContext.enforceCallingOrSelfPermission(
1271 android.Manifest.permission.ACCESS_NETWORK_STATE,
1272 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001273 }
1274
1275 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001276 mContext.enforceCallingOrSelfPermission(
1277 android.Manifest.permission.CHANGE_NETWORK_STATE,
1278 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001279 }
1280
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001281 // TODO Make this a special check when it goes public
1282 private void enforceTetherChangePermission() {
1283 mContext.enforceCallingOrSelfPermission(
1284 android.Manifest.permission.CHANGE_NETWORK_STATE,
1285 "ConnectivityService");
1286 }
1287
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001288 private void enforceTetherAccessPermission() {
1289 mContext.enforceCallingOrSelfPermission(
1290 android.Manifest.permission.ACCESS_NETWORK_STATE,
1291 "ConnectivityService");
1292 }
1293
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001294 private void enforceConnectivityInternalPermission() {
1295 mContext.enforceCallingOrSelfPermission(
1296 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1297 "ConnectivityService");
1298 }
1299
The Android Open Source Project28527d22009-03-03 19:31:44 -08001300 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001301 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1302 * network, we ignore it. If it is for the active network, we send out a
1303 * broadcast. But first, we check whether it might be possible to connect
1304 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001305 * @param info the {@code NetworkInfo} for the network
1306 */
1307 private void handleDisconnect(NetworkInfo info) {
1308
Robert Greenwalt2034b912009-08-12 16:08:25 -07001309 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001310
Robert Greenwalt2034b912009-08-12 16:08:25 -07001311 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001312 /*
1313 * If the disconnected network is not the active one, then don't report
1314 * this as a loss of connectivity. What probably happened is that we're
1315 * getting the disconnect for a network that we explicitly disabled
1316 * in accordance with network preference policies.
1317 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001318 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001319 List pids = mNetRequestersPids[prevNetType];
1320 for (int i = 0; i<pids.size(); i++) {
1321 Integer pid = (Integer)pids.get(i);
1322 // will remove them because the net's no longer connected
1323 // need to do this now as only now do we know the pids and
1324 // can properly null things that are no longer referenced.
1325 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001326 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001327 }
1328
The Android Open Source Project28527d22009-03-03 19:31:44 -08001329 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1330 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1331 if (info.isFailover()) {
1332 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1333 info.setFailover(false);
1334 }
1335 if (info.getReason() != null) {
1336 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1337 }
1338 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001339 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1340 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001341 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001342
Robert Greenwalt34848c02011-03-25 13:09:25 -07001343 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001344 tryFailover(prevNetType);
1345 if (mActiveDefaultNetwork != -1) {
1346 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001347 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1348 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001349 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001350 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1351 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001352 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001353 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001354
1355 // Reset interface if no other connections are using the same interface
1356 boolean doReset = true;
1357 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1358 if (linkProperties != null) {
1359 String oldIface = linkProperties.getInterfaceName();
1360 if (TextUtils.isEmpty(oldIface) == false) {
1361 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1362 if (networkStateTracker == null) continue;
1363 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1364 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1365 LinkProperties l = networkStateTracker.getLinkProperties();
1366 if (l == null) continue;
1367 if (oldIface.equals(l.getInterfaceName())) {
1368 doReset = false;
1369 break;
1370 }
1371 }
1372 }
1373 }
1374 }
1375
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001376 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001377 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001378
1379 sendStickyBroadcast(intent);
1380 /*
1381 * If the failover network is already connected, then immediately send
1382 * out a followup broadcast indicating successful failover
1383 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001384 if (mActiveDefaultNetwork != -1) {
1385 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001386 }
1387 }
1388
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001389 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001390 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001391 * If this is a default network, check if other defaults are available.
1392 * Try to reconnect on all available and let them hash it out when
1393 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001394 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001395 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001396 if (mActiveDefaultNetwork == prevNetType) {
1397 mActiveDefaultNetwork = -1;
1398 }
1399
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001400 // don't signal a reconnect for anything lower or equal priority than our
1401 // current connected default
1402 // TODO - don't filter by priority now - nice optimization but risky
1403// int currentPriority = -1;
1404// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001405// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001406// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001407 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001408 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001409 if (mNetConfigs[checkType] == null) continue;
1410 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001411
1412// Enabling the isAvailable() optimization caused mobile to not get
1413// selected if it was in the middle of error handling. Specifically
1414// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1415// would not be available and we wouldn't get connected to anything.
1416// So removing the isAvailable() optimization below for now. TODO: This
1417// optimization should work and we need to investigate why it doesn't work.
1418// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1419// complete before it is really complete.
1420// if (!mNetTrackers[checkType].isAvailable()) continue;
1421
Robert Greenwalt34848c02011-03-25 13:09:25 -07001422// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001423
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001424 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1425 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1426 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1427 checkInfo.setFailover(true);
1428 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001429 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001430 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001431 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001432 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001433 }
1434
1435 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001436 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1437 }
1438
1439 private void sendInetConditionBroadcast(NetworkInfo info) {
1440 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1441 }
1442
1443 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1444 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001445 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1446 if (info.isFailover()) {
1447 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1448 info.setFailover(false);
1449 }
1450 if (info.getReason() != null) {
1451 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1452 }
1453 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001454 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1455 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001456 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001457 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001458 sendStickyBroadcast(intent);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001459 }
1460
1461 /**
1462 * Called when an attempt to fail over to another network has failed.
1463 * @param info the {@link NetworkInfo} for the failed network
1464 */
1465 private void handleConnectionFailure(NetworkInfo info) {
1466 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001467
Robert Greenwalt2034b912009-08-12 16:08:25 -07001468 String reason = info.getReason();
1469 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001470
Robert Greenwalte981bc52010-10-08 16:35:52 -07001471 String reasonText;
1472 if (reason == null) {
1473 reasonText = ".";
1474 } else {
1475 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001476 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001477 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001478
1479 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1480 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1481 if (getActiveNetworkInfo() == null) {
1482 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1483 }
1484 if (reason != null) {
1485 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1486 }
1487 if (extraInfo != null) {
1488 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1489 }
1490 if (info.isFailover()) {
1491 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1492 info.setFailover(false);
1493 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001494
Robert Greenwalt34848c02011-03-25 13:09:25 -07001495 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001496 tryFailover(info.getType());
1497 if (mActiveDefaultNetwork != -1) {
1498 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001499 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1500 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001501 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001502 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1503 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001504 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001505
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001506 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001507 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001508 /*
1509 * If the failover network is already connected, then immediately send
1510 * out a followup broadcast indicating successful failover
1511 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001512 if (mActiveDefaultNetwork != -1) {
1513 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001514 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001515 }
1516
1517 private void sendStickyBroadcast(Intent intent) {
1518 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001519 if (!mSystemReady) {
1520 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001521 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001522 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1523 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001524 }
1525 }
1526
1527 void systemReady() {
1528 synchronized(this) {
1529 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001530 if (mInitialBroadcast != null) {
1531 mContext.sendStickyBroadcast(mInitialBroadcast);
1532 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001533 }
1534 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001535 // load the global proxy at startup
1536 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001537 }
1538
1539 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001540 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001541
1542 // snapshot isFailover, because sendConnectedBroadcast() resets it
1543 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001544 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001545
Robert Greenwalt2034b912009-08-12 16:08:25 -07001546 // if this is a default net and other default is running
1547 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001548 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001549 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1550 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001551 mNetConfigs[mActiveDefaultNetwork].priority >
1552 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001553 mNetworkPreference == mActiveDefaultNetwork) {
1554 // don't accept this one
Wink Savillee70c6f52010-12-03 12:01:38 -08001555 if (DBG) {
1556 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001557 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001558 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001559 teardown(thisNet);
1560 return;
1561 } else {
1562 // tear down the other
1563 NetworkStateTracker otherNet =
1564 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001565 if (DBG) {
1566 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001567 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001568 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001569 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001570 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001571 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001572 return;
1573 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001574 }
1575 }
1576 synchronized (ConnectivityService.this) {
1577 // have a new default network, release the transition wakelock in a second
1578 // if it's held. The second pause is to allow apps to reconnect over the
1579 // new network
1580 if (mNetTransitionWakeLock.isHeld()) {
1581 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001582 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001583 mNetTransitionWakeLockSerialNumber, 0),
1584 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001585 }
1586 }
1587 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001588 // this will cause us to come up initially as unconnected and switching
1589 // to connected after our normal pause unless somebody reports us as reall
1590 // disconnected
1591 mDefaultInetConditionPublished = 0;
1592 mDefaultConnectionSequence++;
1593 mInetConditionChangeInFlight = false;
1594 // Don't do this - if we never sign in stay, grey
1595 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001596 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001597 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001598 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001599 handleConnectivityChange(type, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001600 sendConnectedBroadcast(info);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001601 }
1602
The Android Open Source Project28527d22009-03-03 19:31:44 -08001603 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001604 * After a change in the connectivity state of a network. We're mainly
1605 * concerned with making sure that the list of DNS servers is set up
1606 * according to which networks are connected, and ensuring that the
1607 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001608 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001609 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001610 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1611
The Android Open Source Project28527d22009-03-03 19:31:44 -08001612 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001613 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001614 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001615 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001616 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001617
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001618 LinkProperties curLp = mCurrentLinkProperties[netType];
1619 LinkProperties newLp = null;
1620
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001621 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001622 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001623 if (VDBG) {
1624 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1625 " doReset=" + doReset + " resetMask=" + resetMask +
1626 "\n curLp=" + curLp +
1627 "\n newLp=" + newLp);
1628 }
1629
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001630 if (curLp != null) {
1631 if (curLp.isIdenticalInterfaceName(newLp)) {
1632 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1633 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1634 for (LinkAddress linkAddr : car.removed) {
1635 if (linkAddr.getAddress() instanceof Inet4Address) {
1636 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1637 }
1638 if (linkAddr.getAddress() instanceof Inet6Address) {
1639 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1640 }
Wink Saville051a6642011-07-13 13:44:13 -07001641 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001642 if (DBG) {
1643 log("handleConnectivityChange: addresses changed" +
1644 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1645 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001646 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001647 } else {
1648 if (DBG) {
1649 log("handleConnectivityChange: address are the same reset per doReset" +
1650 " linkProperty[" + netType + "]:" +
1651 " resetMask=" + resetMask);
1652 }
Wink Saville051a6642011-07-13 13:44:13 -07001653 }
1654 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001655 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
1656 log("handleConnectivityChange: interface not not equivalent reset both" +
1657 " linkProperty[" + netType + "]:" +
1658 " resetMask=" + resetMask);
Wink Saville051a6642011-07-13 13:44:13 -07001659 }
Wink Saville051a6642011-07-13 13:44:13 -07001660 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001661 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001662 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001663 }
1664 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001665 if (VDBG) {
1666 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1667 " doReset=" + doReset + " resetMask=" + resetMask +
1668 "\n curLp=" + curLp +
1669 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001670 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001671 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001672 mCurrentLinkProperties[netType] = newLp;
1673 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001674
Wink Saville051a6642011-07-13 13:44:13 -07001675 if (doReset || resetMask != 0) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001676 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1677 if (linkProperties != null) {
1678 String iface = linkProperties.getInterfaceName();
1679 if (TextUtils.isEmpty(iface) == false) {
Wink Saville051a6642011-07-13 13:44:13 -07001680 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1681 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001682 }
1683 }
1684 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001685
1686 // TODO: Temporary notifying upstread change to Tethering.
1687 // @see bug/4455071
1688 /** Notify TetheringService if interface name has been changed. */
1689 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1690 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1691 if (isTetheringSupported()) {
1692 mTethering.handleTetherIfaceChange();
1693 }
1694 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001695 }
1696
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001697 /**
1698 * Add and remove routes using the old properties (null if not previously connected),
1699 * new properties (null if becoming disconnected). May even be double null, which
1700 * is a noop.
1701 * Uses isLinkDefault to determine if default routes should be set or conversely if
1702 * host routes should be set to the dns servers
1703 */
1704 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1705 Collection<RouteInfo> routesToAdd = null;
1706 CompareResult<InetAddress> dnsDiff = null;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001707
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001708 if (curLp != null) {
1709 // check for the delta between the current set and the new
1710 CompareResult<RouteInfo> routeDiff = curLp.compareRoutes(newLp);
1711 dnsDiff = curLp.compareDnses(newLp);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001712
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001713 for (RouteInfo r : routeDiff.removed) {
1714 if (isLinkDefault || ! r.isDefaultRoute()) {
1715 removeRoute(curLp, r);
Robert Greenwalt355205c2011-05-10 15:05:02 -07001716 }
1717 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001718 routesToAdd = routeDiff.added;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001719 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001720
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001721 if (newLp != null) {
1722 // if we didn't get a diff from cur -> new, then just use the new
1723 if (routesToAdd == null) {
1724 routesToAdd = newLp.getRoutes();
1725 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001726
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001727 for (RouteInfo r : routesToAdd) {
1728 if (isLinkDefault || ! r.isDefaultRoute()) {
1729 addRoute(newLp, r);
1730 }
1731 }
1732 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001733
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001734 if (!isLinkDefault) {
1735 // handle DNS routes
1736 Collection<InetAddress> dnsToAdd = null;
1737 if (dnsDiff != null) {
1738 dnsToAdd = dnsDiff.added;
1739 for (InetAddress dnsAddress : dnsDiff.removed) {
1740 removeRoute(curLp, RouteInfo.makeHostRoute(dnsAddress));
1741 }
1742 }
1743 if (newLp != null) {
1744 if (dnsToAdd == null) {
1745 dnsToAdd = newLp.getDnses();
1746 }
1747 for(InetAddress dnsAddress : dnsToAdd) {
1748 addRoute(newLp, RouteInfo.makeHostRoute(dnsAddress));
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001749 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001750 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001751 }
1752 }
1753
1754
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001755 /**
1756 * Reads the network specific TCP buffer sizes from SystemProperties
1757 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1758 * wide use
1759 */
1760 public void updateNetworkSettings(NetworkStateTracker nt) {
1761 String key = nt.getTcpBufferSizesPropName();
1762 String bufferSizes = SystemProperties.get(key);
1763
1764 if (bufferSizes.length() == 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001765 loge(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001766
1767 // Setting to default values so we won't be stuck to previous values
1768 key = "net.tcp.buffersize.default";
1769 bufferSizes = SystemProperties.get(key);
1770 }
1771
1772 // Set values in kernel
1773 if (bufferSizes.length() != 0) {
1774 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001775 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001776 + "] which comes from [" + key + "]");
1777 }
1778 setBufferSize(bufferSizes);
1779 }
1780 }
1781
1782 /**
1783 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1784 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1785 *
1786 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1787 * writeMin, writeInitial, writeMax"
1788 */
1789 private void setBufferSize(String bufferSizes) {
1790 try {
1791 String[] values = bufferSizes.split(",");
1792
1793 if (values.length == 6) {
1794 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001795 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1796 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1797 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1798 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1799 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1800 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001801 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001802 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001803 }
1804 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001805 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001806 }
1807 }
1808
Robert Greenwalt2034b912009-08-12 16:08:25 -07001809 /**
1810 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1811 * on the highest priority active net which this process requested.
1812 * If there aren't any, clear it out
1813 */
1814 private void reassessPidDns(int myPid, boolean doBump)
1815 {
Wink Savillee70c6f52010-12-03 12:01:38 -08001816 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001817 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001818 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001819 continue;
1820 }
1821 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001822 if (nt.getNetworkInfo().isConnected() &&
1823 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001824 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001825 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001826 List pids = mNetRequestersPids[i];
1827 for (int j=0; j<pids.size(); j++) {
1828 Integer pid = (Integer)pids.get(j);
1829 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001830 Collection<InetAddress> dnses = p.getDnses();
1831 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001832 if (doBump) {
1833 bumpDns();
1834 }
1835 return;
1836 }
1837 }
1838 }
1839 }
1840 // nothing found - delete
1841 for (int i = 1; ; i++) {
1842 String prop = "net.dns" + i + "." + myPid;
1843 if (SystemProperties.get(prop).length() == 0) {
1844 if (doBump) {
1845 bumpDns();
1846 }
1847 return;
1848 }
1849 SystemProperties.set(prop, "");
1850 }
1851 }
1852
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001853 // return true if results in a change
1854 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001855 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001856 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001857 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001858 String dnsString = dns.getHostAddress();
1859 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1860 changed = true;
1861 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1862 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001863 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001864 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001865 }
1866
1867 private void bumpDns() {
1868 /*
1869 * Bump the property that tells the name resolver library to reread
1870 * the DNS server list from the properties.
1871 */
1872 String propVal = SystemProperties.get("net.dnschange");
1873 int n = 0;
1874 if (propVal.length() != 0) {
1875 try {
1876 n = Integer.parseInt(propVal);
1877 } catch (NumberFormatException e) {}
1878 }
1879 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001880 /*
1881 * Tell the VMs to toss their DNS caches
1882 */
1883 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1884 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08001885 /*
1886 * Connectivity events can happen before boot has completed ...
1887 */
1888 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07001889 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001890 }
1891
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001892 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001893 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001894 NetworkStateTracker nt = mNetTrackers[netType];
1895 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001896 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001897 if (p == null) return;
1898 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001899 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001900 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001901 int j = 1;
Robert Greenwalt94daa182010-09-01 11:34:05 -07001902 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001903 String dnsString = mDefaultDns.getHostAddress();
1904 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1905 if (DBG) {
1906 log("no dns provided - using " + dnsString);
1907 }
1908 changed = true;
1909 SystemProperties.set("net.dns1", dnsString);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001910 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001911 j++;
1912 } else {
1913 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001914 String dnsString = dns.getHostAddress();
1915 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1916 j++;
1917 continue;
1918 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001919 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001920 log("adding dns " + dns + " for " +
Robert Greenwalt94daa182010-09-01 11:34:05 -07001921 nt.getNetworkInfo().getTypeName());
1922 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001923 changed = true;
1924 SystemProperties.set("net.dns" + j++, dnsString);
Robert Greenwalt94daa182010-09-01 11:34:05 -07001925 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001926 }
1927 for (int k=j ; k<mNumDnsEntries; k++) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001928 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1929 if (DBG) log("erasing net.dns" + k);
1930 changed = true;
1931 SystemProperties.set("net.dns" + k, "");
1932 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001933 }
1934 mNumDnsEntries = j;
1935 } else {
1936 // set per-pid dns for attached secondary nets
1937 List pids = mNetRequestersPids[netType];
1938 for (int y=0; y< pids.size(); y++) {
1939 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001940 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001941 }
1942 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001943 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001944 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001945 }
1946
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001947 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001948 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1949 NETWORK_RESTORE_DELAY_PROP_NAME);
1950 if(restoreDefaultNetworkDelayStr != null &&
1951 restoreDefaultNetworkDelayStr.length() != 0) {
1952 try {
1953 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1954 } catch (NumberFormatException e) {
1955 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001956 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001957 // if the system property isn't set, use the value for the apn type
1958 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1959
1960 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1961 (mNetConfigs[networkType] != null)) {
1962 ret = mNetConfigs[networkType].restoreTime;
1963 }
1964 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001965 }
1966
1967 @Override
1968 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001969 if (mContext.checkCallingOrSelfPermission(
1970 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001971 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001972 pw.println("Permission Denial: can't dump ConnectivityService " +
1973 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1974 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001975 return;
1976 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001977 pw.println();
1978 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001979 if (nst != null) {
1980 if (nst.getNetworkInfo().isConnected()) {
1981 pw.println("Active network: " + nst.getNetworkInfo().
1982 getTypeName());
1983 }
1984 pw.println(nst.getNetworkInfo());
1985 pw.println(nst);
1986 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001987 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001988 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001989
1990 pw.println("Network Requester Pids:");
1991 for (int net : mPriorityList) {
1992 String pidString = net + ": ";
1993 for (Object pid : mNetRequestersPids[net]) {
1994 pidString = pidString + pid.toString() + ", ";
1995 }
1996 pw.println(pidString);
1997 }
1998 pw.println();
1999
2000 pw.println("FeatureUsers:");
2001 for (Object requester : mFeatureUsers) {
2002 pw.println(requester.toString());
2003 }
2004 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002005
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002006 synchronized (this) {
2007 pw.println("NetworkTranstionWakeLock is currently " +
2008 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2009 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2010 }
2011 pw.println();
2012
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002013 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002014
2015 if (mInetLog != null) {
2016 pw.println();
2017 pw.println("Inet condition reports:");
2018 for(int i = 0; i < mInetLog.size(); i++) {
2019 pw.println(mInetLog.get(i));
2020 }
2021 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002022 }
2023
Robert Greenwalt2034b912009-08-12 16:08:25 -07002024 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002025 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07002026 public MyHandler(Looper looper) {
2027 super(looper);
2028 }
2029
The Android Open Source Project28527d22009-03-03 19:31:44 -08002030 @Override
2031 public void handleMessage(Message msg) {
2032 NetworkInfo info;
2033 switch (msg.what) {
2034 case NetworkStateTracker.EVENT_STATE_CHANGED:
2035 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002036 int type = info.getType();
2037 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002038
Wink Savillee70c6f52010-12-03 12:01:38 -08002039 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002040 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002041 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002042
2043 // Connectivity state changed:
2044 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002045 // [12-9] Network subtype (for mobile network, as defined
2046 // by TelephonyManager)
2047 // [8-3] Detailed state ordinal (as defined by
2048 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002049 // [2-0] Network type (as defined by ConnectivityManager)
2050 int eventLogParam = (info.getType() & 0x7) |
2051 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2052 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002053 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002054 eventLogParam);
2055
2056 if (info.getDetailedState() ==
2057 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002058 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002059 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002060 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002061 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002062 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002063 // the logic here is, handle SUSPENDED the same as
2064 // DISCONNECTED. The only difference being we are
2065 // broadcasting an intent with NetworkInfo that's
2066 // suspended. This allows the applications an
2067 // opportunity to handle DISCONNECTED and SUSPENDED
2068 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002069 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002070 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002071 handleConnect(info);
2072 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002073 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002074 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002075 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002076 // TODO: Temporary allowing network configuration
2077 // change not resetting sockets.
2078 // @see bug/4455071
2079 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002080 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002081 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002082 String causedBy = null;
2083 synchronized (ConnectivityService.this) {
2084 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2085 mNetTransitionWakeLock.isHeld()) {
2086 mNetTransitionWakeLock.release();
2087 causedBy = mNetTransitionWakeLockCausedBy;
2088 }
2089 }
2090 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002091 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002092 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002093 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002094 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002095 FeatureUser u = (FeatureUser)msg.obj;
2096 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002097 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002098 case EVENT_INET_CONDITION_CHANGE:
2099 {
2100 int netType = msg.arg1;
2101 int condition = msg.arg2;
2102 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002103 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002104 }
2105 case EVENT_INET_CONDITION_HOLD_END:
2106 {
2107 int netType = msg.arg1;
2108 int sequence = msg.arg2;
2109 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002110 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002111 }
2112 case EVENT_SET_NETWORK_PREFERENCE:
2113 {
2114 int preference = msg.arg1;
2115 handleSetNetworkPreference(preference);
2116 break;
2117 }
2118 case EVENT_SET_BACKGROUND_DATA:
2119 {
2120 boolean enabled = (msg.arg1 == ENABLED);
2121 handleSetBackgroundData(enabled);
2122 break;
2123 }
2124 case EVENT_SET_MOBILE_DATA:
2125 {
2126 boolean enabled = (msg.arg1 == ENABLED);
2127 handleSetMobileData(enabled);
2128 break;
2129 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002130 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2131 {
2132 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002133 break;
2134 }
2135 case EVENT_SET_DEPENDENCY_MET:
2136 {
2137 boolean met = (msg.arg1 == ENABLED);
2138 handleSetDependencyMet(msg.arg2, met);
2139 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002140 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002141 }
2142 }
2143 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002144
2145 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002146 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002147 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002148
2149 if (isTetheringSupported()) {
2150 return mTethering.tether(iface);
2151 } else {
2152 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2153 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002154 }
2155
2156 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002157 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002158 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002159
2160 if (isTetheringSupported()) {
2161 return mTethering.untether(iface);
2162 } else {
2163 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2164 }
2165 }
2166
2167 // javadoc from interface
2168 public int getLastTetherError(String iface) {
2169 enforceTetherAccessPermission();
2170
2171 if (isTetheringSupported()) {
2172 return mTethering.getLastTetherError(iface);
2173 } else {
2174 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2175 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002176 }
2177
2178 // TODO - proper iface API for selection by property, inspection, etc
2179 public String[] getTetherableUsbRegexs() {
2180 enforceTetherAccessPermission();
2181 if (isTetheringSupported()) {
2182 return mTethering.getTetherableUsbRegexs();
2183 } else {
2184 return new String[0];
2185 }
2186 }
2187
2188 public String[] getTetherableWifiRegexs() {
2189 enforceTetherAccessPermission();
2190 if (isTetheringSupported()) {
2191 return mTethering.getTetherableWifiRegexs();
2192 } else {
2193 return new String[0];
2194 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002195 }
2196
Danica Chang96567052010-08-11 14:54:43 -07002197 public String[] getTetherableBluetoothRegexs() {
2198 enforceTetherAccessPermission();
2199 if (isTetheringSupported()) {
2200 return mTethering.getTetherableBluetoothRegexs();
2201 } else {
2202 return new String[0];
2203 }
2204 }
2205
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002206 // TODO - move iface listing, queries, etc to new module
2207 // javadoc from interface
2208 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002209 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002210 return mTethering.getTetherableIfaces();
2211 }
2212
2213 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002214 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002215 return mTethering.getTetheredIfaces();
2216 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002217
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002218 public String[] getTetheringErroredIfaces() {
2219 enforceTetherAccessPermission();
2220 return mTethering.getErroredIfaces();
2221 }
2222
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002223 // if ro.tether.denied = true we default to no tethering
2224 // gservices could set the secure setting to 1 though to enable it on a build where it
2225 // had previously been turned off.
2226 public boolean isTetheringSupported() {
2227 enforceTetherAccessPermission();
2228 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002229 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2230 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2231 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002232 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002233
2234 // An API NetworkStateTrackers can call when they lose their network.
2235 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2236 // whichever happens first. The timer is started by the first caller and not
2237 // restarted by subsequent callers.
2238 public void requestNetworkTransitionWakelock(String forWhom) {
2239 enforceConnectivityInternalPermission();
2240 synchronized (this) {
2241 if (mNetTransitionWakeLock.isHeld()) return;
2242 mNetTransitionWakeLockSerialNumber++;
2243 mNetTransitionWakeLock.acquire();
2244 mNetTransitionWakeLockCausedBy = forWhom;
2245 }
2246 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002247 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002248 mNetTransitionWakeLockSerialNumber, 0),
2249 mNetTransitionWakeLockTimeout);
2250 return;
2251 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002252
Robert Greenwalt986c7412010-09-08 15:24:47 -07002253 // 100 percent is full good, 0 is full bad.
2254 public void reportInetCondition(int networkType, int percentage) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002255 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002256 mContext.enforceCallingOrSelfPermission(
2257 android.Manifest.permission.STATUS_BAR,
2258 "ConnectivityService");
2259
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002260 if (DBG) {
2261 int pid = getCallingPid();
2262 int uid = getCallingUid();
2263 String s = pid + "(" + uid + ") reports inet is " +
2264 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2265 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2266 mInetLog.add(s);
2267 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2268 mInetLog.remove(0);
2269 }
2270 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002271 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002272 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2273 }
2274
2275 private void handleInetConditionChange(int netType, int condition) {
2276 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002277 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002278 netType + ", condition=" + condition +
2279 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2280 }
2281 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002282 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002283 return;
2284 }
2285 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002286 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002287 return;
2288 }
2289 mDefaultInetCondition = condition;
2290 int delay;
2291 if (mInetConditionChangeInFlight == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002292 if (DBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002293 // setup a new hold to debounce this
2294 if (mDefaultInetCondition > 50) {
2295 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2296 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2297 } else {
2298 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2299 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2300 }
2301 mInetConditionChangeInFlight = true;
2302 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2303 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2304 } else {
2305 // we've set the new condition, when this hold ends that will get
2306 // picked up
Wink Savillee70c6f52010-12-03 12:01:38 -08002307 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002308 }
2309 }
2310
2311 private void handleInetConditionHoldEnd(int netType, int sequence) {
2312 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002313 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002314 ", condition =" + mDefaultInetCondition +
2315 ", published condition =" + mDefaultInetConditionPublished);
2316 }
2317 mInetConditionChangeInFlight = false;
2318
2319 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002320 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002321 return;
2322 }
2323 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002324 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002325 return;
2326 }
2327 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002328 if (DBG) log("no change in condition - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002329 return;
2330 }
2331 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2332 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002333 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002334 return;
2335 }
2336 mDefaultInetConditionPublished = mDefaultInetCondition;
2337 sendInetConditionBroadcast(networkInfo);
2338 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002339 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002340
2341 public synchronized ProxyProperties getProxy() {
2342 if (mGlobalProxy != null) return mGlobalProxy;
2343 if (mDefaultProxy != null) return mDefaultProxy;
2344 return null;
2345 }
2346
2347 public void setGlobalProxy(ProxyProperties proxyProperties) {
2348 enforceChangePermission();
2349 synchronized (mGlobalProxyLock) {
2350 if (proxyProperties == mGlobalProxy) return;
2351 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2352 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2353
2354 String host = "";
2355 int port = 0;
2356 String exclList = "";
2357 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2358 mGlobalProxy = new ProxyProperties(proxyProperties);
2359 host = mGlobalProxy.getHost();
2360 port = mGlobalProxy.getPort();
2361 exclList = mGlobalProxy.getExclusionList();
2362 } else {
2363 mGlobalProxy = null;
2364 }
2365 ContentResolver res = mContext.getContentResolver();
2366 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2367 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002368 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002369 exclList);
2370 }
2371
2372 if (mGlobalProxy == null) {
2373 proxyProperties = mDefaultProxy;
2374 }
2375 sendProxyBroadcast(proxyProperties);
2376 }
2377
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002378 private void loadGlobalProxy() {
2379 ContentResolver res = mContext.getContentResolver();
2380 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2381 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2382 String exclList = Settings.Secure.getString(res,
2383 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2384 if (!TextUtils.isEmpty(host)) {
2385 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2386 synchronized (mGlobalProxyLock) {
2387 mGlobalProxy = proxyProperties;
2388 }
2389 }
2390 }
2391
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002392 public ProxyProperties getGlobalProxy() {
2393 synchronized (mGlobalProxyLock) {
2394 return mGlobalProxy;
2395 }
2396 }
2397
2398 private void handleApplyDefaultProxy(int type) {
2399 // check if new default - push it out to all VM if so
2400 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2401 synchronized (this) {
2402 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2403 if (mDefaultProxy == proxy) return;
2404 if (!TextUtils.isEmpty(proxy.getHost())) {
2405 mDefaultProxy = proxy;
2406 } else {
2407 mDefaultProxy = null;
2408 }
2409 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002410 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002411 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2412 if (mGlobalProxy != null) return;
2413 sendProxyBroadcast(proxy);
2414 }
2415
2416 private void handleDeprecatedGlobalHttpProxy() {
2417 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2418 Settings.Secure.HTTP_PROXY);
2419 if (!TextUtils.isEmpty(proxy)) {
2420 String data[] = proxy.split(":");
2421 String proxyHost = data[0];
2422 int proxyPort = 8080;
2423 if (data.length > 1) {
2424 try {
2425 proxyPort = Integer.parseInt(data[1]);
2426 } catch (NumberFormatException e) {
2427 return;
2428 }
2429 }
2430 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2431 setGlobalProxy(p);
2432 }
2433 }
2434
2435 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002436 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savillee70c6f52010-12-03 12:01:38 -08002437 log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002438 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002439 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2440 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002441 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002442 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002443 }
2444
2445 private static class SettingsObserver extends ContentObserver {
2446 private int mWhat;
2447 private Handler mHandler;
2448 SettingsObserver(Handler handler, int what) {
2449 super(handler);
2450 mHandler = handler;
2451 mWhat = what;
2452 }
2453
2454 void observe(Context context) {
2455 ContentResolver resolver = context.getContentResolver();
2456 resolver.registerContentObserver(Settings.Secure.getUriFor(
2457 Settings.Secure.HTTP_PROXY), false, this);
2458 }
2459
2460 @Override
2461 public void onChange(boolean selfChange) {
2462 mHandler.obtainMessage(mWhat).sendToTarget();
2463 }
2464 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002465
2466 private void log(String s) {
2467 Slog.d(TAG, s);
2468 }
2469
2470 private void loge(String s) {
2471 Slog.e(TAG, s);
2472 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002473
Wink Savillef6b76692011-02-24 17:58:51 -08002474 int convertFeatureToNetworkType(String feature){
2475 int networkType = -1;
2476 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2477 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2478 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2479 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2480 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2481 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2482 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2483 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2484 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2485 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2486 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2487 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2488 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2489 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2490 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2491 }
2492 return networkType;
2493 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002494
2495 private static <T> T checkNotNull(T value, String message) {
2496 if (value == null) {
2497 throw new NullPointerException(message);
2498 }
2499 return value;
2500 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002501
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002502 /**
2503 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002504 * VpnBuilder and not available in ConnectivityManager. Permissions
2505 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002506 * @hide
2507 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002508 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07002509 public boolean protectVpn(ParcelFileDescriptor socket) {
2510 try {
2511 int type = mActiveDefaultNetwork;
2512 if (ConnectivityManager.isNetworkTypeValid(type)) {
2513 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2514 return true;
2515 }
2516 } catch (Exception e) {
2517 // ignore
2518 } finally {
2519 try {
2520 socket.close();
2521 } catch (Exception e) {
2522 // ignore
2523 }
2524 }
2525 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002526 }
2527
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002528 /**
2529 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002530 * and not available in ConnectivityManager. Permissions are checked
2531 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002532 * @hide
2533 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002534 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07002535 public boolean prepareVpn(String oldPackage, String newPackage) {
2536 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002537 }
2538
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002539 /**
2540 * Configure a TUN interface and return its file descriptor. Parameters
2541 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002542 * and not available in ConnectivityManager. Permissions are checked in
2543 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002544 * @hide
2545 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002546 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002547 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002548 return mVpn.establish(config);
2549 }
2550
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002551 /**
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002552 * Start legacy VPN and return an intent to VpnDialogs. This method is
2553 * used by VpnSettings and not available in ConnectivityManager.
2554 * Permissions are checked in Vpn class.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002555 * @hide
2556 */
2557 @Override
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07002558 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2559 mVpn.startLegacyVpn(config, racoon, mtpd);
2560 }
2561
2562 /**
2563 * Return the information of the ongoing legacy VPN. This method is used
2564 * by VpnSettings and not available in ConnectivityManager. Permissions
2565 * are checked in Vpn class.
2566 * @hide
2567 */
2568 @Override
2569 public LegacyVpnInfo getLegacyVpnInfo() {
2570 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07002571 }
2572
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002573 /**
2574 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2575 * through NetworkStateTracker since it works differently. For example, it
2576 * needs to override DNS servers but never takes the default routes. It
2577 * relies on another data network, and it could keep existing connections
2578 * alive after reconnecting, switching between networks, or even resuming
2579 * from deep sleep. Calls from applications should be done synchronously
2580 * to avoid race conditions. As these are all hidden APIs, refactoring can
2581 * be done whenever a better abstraction is developed.
2582 */
2583 public class VpnCallback {
2584
2585 private VpnCallback() {
2586 }
2587
Chia-chi Yehd050d1c2011-07-01 01:09:42 -07002588 public synchronized void override(List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002589 // TODO: override DNS servers and http proxy.
2590 }
2591
2592 public synchronized void restore() {
2593 // TODO: restore VPN changes.
2594 }
2595 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002596}