blob: edf1907088624af30df87c5d2dcbb62d7c34f3f9 [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
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080019import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080020import android.content.ContentResolver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070024import android.database.ContentObserver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080025import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080026import android.net.DummyDataStateTracker;
Benoit Goby6cec7f32010-12-22 14:29:40 -080027import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080028import android.net.IConnectivityManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -070029import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080030import android.net.LinkProperties;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070031import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080032import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070033import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080034import android.net.NetworkInfo;
35import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070036import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070037import android.net.Proxy;
38import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070039import android.net.RouteInfo;
Hung-ying Tyan4e723422011-01-19 16:48:38 +080040import android.net.vpn.VpnManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -080041import android.net.wifi.WifiStateTracker;
42import android.os.Binder;
43import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070044import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070045import android.os.IBinder;
Robert Greenwalt355205c2011-05-10 15:05:02 -070046import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080047import android.os.Looper;
48import android.os.Message;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070049import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070050import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080051import android.os.ServiceManager;
52import android.os.SystemProperties;
53import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070054import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080055import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080056import android.util.Slog;
The Android Open Source Project28527d22009-03-03 19:31:44 -080057
Robert Greenwalt2034b912009-08-12 16:08:25 -070058import com.android.internal.telephony.Phone;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080059import com.android.server.connectivity.Tethering;
60
The Android Open Source Project28527d22009-03-03 19:31:44 -080061import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070062import java.io.FileWriter;
63import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080064import java.io.PrintWriter;
Wink Saville051a6642011-07-13 13:44:13 -070065import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070066import java.net.InetAddress;
Robert Greenwalt355205c2011-05-10 15:05:02 -070067import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070068import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -070069import java.util.ArrayList;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070070import java.util.Collection;
Robert Greenwaltd62c7002010-12-29 16:15:02 -080071import java.util.concurrent.atomic.AtomicBoolean;
Robert Greenwalt0e80be12010-09-20 14:35:25 -070072import java.util.GregorianCalendar;
Robert Greenwalt2034b912009-08-12 16:08:25 -070073import java.util.List;
The Android Open Source Project28527d22009-03-03 19:31:44 -080074
75/**
76 * @hide
77 */
78public class ConnectivityService extends IConnectivityManager.Stub {
79
Robert Greenwalt063dc7d2010-10-05 19:12:26 -070080 private static final boolean DBG = true;
Wink Saville051a6642011-07-13 13:44:13 -070081 private static final boolean VDBG = true;
The Android Open Source Project28527d22009-03-03 19:31:44 -080082 private static final String TAG = "ConnectivityService";
83
Robert Greenwalt2034b912009-08-12 16:08:25 -070084 // how long to wait before switching back to a radio's default network
85 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
86 // system property that can override the above value
87 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
88 "android.telephony.apn-restore";
89
Robert Greenwaltbd492212011-05-06 17:10:53 -070090 // used in recursive route setting to add gateways for the host for which
91 // a host route was requested.
92 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
93
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080094 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -080095 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080096
The Android Open Source Project28527d22009-03-03 19:31:44 -080097 /**
98 * Sometimes we want to refer to the individual network state
99 * trackers separately, and sometimes we just want to treat them
100 * abstractly.
101 */
102 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700103
104 /**
Wink Saville051a6642011-07-13 13:44:13 -0700105 * The link properties that define the current links
106 */
107 private LinkProperties mCurrentLinkProperties[];
108
109 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700110 * A per Net list of the PID's that requested access to the net
111 * used both as a refcount and for per-PID DNS selection
112 */
113 private List mNetRequestersPids[];
114
Irfan Sheriff653e2a22010-06-07 09:03:04 -0700115 private WifiWatchdogService mWifiWatchdogService;
116
Robert Greenwalt2034b912009-08-12 16:08:25 -0700117 // priority order of the nettrackers
118 // (excluding dynamically set mNetworkPreference)
119 // TODO - move mNetworkTypePreference into this
120 private int[] mPriorityList;
121
The Android Open Source Project28527d22009-03-03 19:31:44 -0800122 private Context mContext;
123 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700124 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700125 // 0 is full bad, 100 is full good
126 private int mDefaultInetCondition = 0;
127 private int mDefaultInetConditionPublished = 0;
128 private boolean mInetConditionChangeInFlight = false;
129 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800130
131 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800132
133 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700134 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800135
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800136 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
137
Robert Greenwalt355205c2011-05-10 15:05:02 -0700138 private INetworkManagementService mNetd;
139
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700140 private static final int ENABLED = 1;
141 private static final int DISABLED = 0;
142
143 // Share the event space with NetworkStateTracker (which can't see this
144 // internal class but sends us events). If you change these, change
145 // NetworkStateTracker.java too.
146 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
147 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
148
149 /**
150 * used internally as a delayed event to make us switch back to the
151 * default network
152 */
153 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
154 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
155
156 /**
157 * used internally to change our mobile data enabled flag
158 */
159 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
160 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
161
162 /**
163 * used internally to change our network preference setting
164 * arg1 = networkType to prefer
165 */
166 private static final int EVENT_SET_NETWORK_PREFERENCE =
167 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
168
169 /**
170 * used internally to synchronize inet condition reports
171 * arg1 = networkType
172 * arg2 = condition (0 bad, 100 good)
173 */
174 private static final int EVENT_INET_CONDITION_CHANGE =
175 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
176
177 /**
178 * used internally to mark the end of inet condition hold periods
179 * arg1 = networkType
180 */
181 private static final int EVENT_INET_CONDITION_HOLD_END =
182 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
183
184 /**
185 * used internally to set the background data preference
186 * arg1 = TRUE for enabled, FALSE for disabled
187 */
188 private static final int EVENT_SET_BACKGROUND_DATA =
189 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
190
191 /**
192 * used internally to set enable/disable cellular data
193 * arg1 = ENBALED or DISABLED
194 */
195 private static final int EVENT_SET_MOBILE_DATA =
196 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
197
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700198 /**
199 * used internally to clear a wakelock when transitioning
200 * from one net to another
201 */
202 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
203 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
204
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700205 /**
206 * used internally to reload global proxy settings
207 */
208 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
209 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
210
Robert Greenwalt34848c02011-03-25 13:09:25 -0700211 /**
212 * used internally to set external dependency met/unmet
213 * arg1 = ENABLED (met) or DISABLED (unmet)
214 * arg2 = NetworkType
215 */
216 private static final int EVENT_SET_DEPENDENCY_MET =
217 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
218
Robert Greenwalt2034b912009-08-12 16:08:25 -0700219 private Handler mHandler;
220
221 // list of DeathRecipients used to make sure features are turned off when
222 // a process dies
223 private List mFeatureUsers;
224
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400225 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800226 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400227
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700228 private PowerManager.WakeLock mNetTransitionWakeLock;
229 private String mNetTransitionWakeLockCausedBy = "";
230 private int mNetTransitionWakeLockSerialNumber;
231 private int mNetTransitionWakeLockTimeout;
232
Robert Greenwalt94daa182010-09-01 11:34:05 -0700233 private InetAddress mDefaultDns;
234
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700235 // this collection is used to refcount the added routes - if there are none left
236 // it's time to remove the route from the route table
237 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
238
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700239 // used in DBG mode to track inet condition reports
240 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
241 private ArrayList mInetLog;
242
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700243 // track the current default http proxy - tell the world if we get a new one (real change)
244 private ProxyProperties mDefaultProxy = null;
245 // track the global proxy.
246 private ProxyProperties mGlobalProxy = null;
247 private final Object mGlobalProxyLock = new Object();
248
249 private SettingsObserver mSettingsObserver;
250
Robert Greenwalt34848c02011-03-25 13:09:25 -0700251 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700252 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700253
Robert Greenwalt12c44552009-12-07 11:33:18 -0800254 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700255 public int mSimultaneity;
256 public int mType;
257 public RadioAttributes(String init) {
258 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700259 mType = Integer.parseInt(fragments[0]);
260 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700261 }
262 }
263 RadioAttributes[] mRadioAttributes;
264
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700265 // the set of network types that can only be enabled by system/sig apps
266 List mProtectedNetworks;
267
Wink Saville775aad62010-09-02 19:23:52 -0700268 public static synchronized ConnectivityService getInstance(Context context) {
269 if (sServiceInstance == null) {
270 sServiceInstance = new ConnectivityService(context);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800271 }
Wink Saville775aad62010-09-02 19:23:52 -0700272 return sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800273 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700274
The Android Open Source Project28527d22009-03-03 19:31:44 -0800275 private ConnectivityService(Context context) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800276 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800277
Wink Saville775aad62010-09-02 19:23:52 -0700278 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
279 handlerThread.start();
280 mHandler = new MyHandler(handlerThread.getLooper());
281
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800282 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
283 Settings.Secure.BACKGROUND_DATA, 1) == 1);
284
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800285 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800286 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
287 String id = Settings.Secure.getString(context.getContentResolver(),
288 Settings.Secure.ANDROID_ID);
289 if (id != null && id.length() > 0) {
290 String name = new String("android_").concat(id);
291 SystemProperties.set("net.hostname", name);
292 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800293 }
294
Robert Greenwalt94daa182010-09-01 11:34:05 -0700295 // read our default dns server ip
296 String dns = Settings.Secure.getString(context.getContentResolver(),
297 Settings.Secure.DEFAULT_DNS_SERVER);
298 if (dns == null || dns.length() == 0) {
299 dns = context.getResources().getString(
300 com.android.internal.R.string.config_default_dns_server);
301 }
302 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800303 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
304 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800305 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700306 }
307
The Android Open Source Project28527d22009-03-03 19:31:44 -0800308 mContext = context;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700309
310 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
311 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
312 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
313 com.android.internal.R.integer.config_networkTransitionTimeout);
314
Robert Greenwalt2034b912009-08-12 16:08:25 -0700315 mNetTrackers = new NetworkStateTracker[
316 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700317 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700318
The Android Open Source Project28527d22009-03-03 19:31:44 -0800319 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700320
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700321 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700322 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700323
Robert Greenwalt2034b912009-08-12 16:08:25 -0700324 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700325 String[] raStrings = context.getResources().getStringArray(
326 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700327 for (String raString : raStrings) {
328 RadioAttributes r = new RadioAttributes(raString);
329 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800330 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700331 continue;
332 }
333 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800334 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700335 r.mType);
336 continue;
337 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700338 mRadioAttributes[r.mType] = r;
339 }
340
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700341 String[] naStrings = context.getResources().getStringArray(
342 com.android.internal.R.array.networkAttributes);
343 for (String naString : naStrings) {
344 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700345 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700346 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800347 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700348 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700349 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700350 }
Wink Savillef2a62832011-04-07 14:23:45 -0700351 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800352 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700353 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700354 continue;
355 }
Wink Savillef2a62832011-04-07 14:23:45 -0700356 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800357 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700358 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700359 continue;
360 }
Wink Savillef2a62832011-04-07 14:23:45 -0700361 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700362 mNetworksDefined++;
363 } catch(Exception e) {
364 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700365 }
366 }
367
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700368 mProtectedNetworks = new ArrayList<Integer>();
369 int[] protectedNetworks = context.getResources().getIntArray(
370 com.android.internal.R.array.config_protectedNetworks);
371 for (int p : protectedNetworks) {
372 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
373 mProtectedNetworks.add(p);
374 } else {
375 if (DBG) loge("Ignoring protectedNetwork " + p);
376 }
377 }
378
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700379 // high priority first
380 mPriorityList = new int[mNetworksDefined];
381 {
382 int insertionPoint = mNetworksDefined-1;
383 int currentLowest = 0;
384 int nextLowest = 0;
385 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700386 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700387 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700388 if (na.priority < currentLowest) continue;
389 if (na.priority > currentLowest) {
390 if (na.priority < nextLowest || nextLowest == 0) {
391 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700392 }
393 continue;
394 }
Wink Savillef2a62832011-04-07 14:23:45 -0700395 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700396 }
397 currentLowest = nextLowest;
398 nextLowest = 0;
399 }
400 }
401
402 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
403 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700404 mNetRequestersPids[i] = new ArrayList();
405 }
406
407 mFeatureUsers = new ArrayList();
408
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700409 mNumDnsEntries = 0;
410
411 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
412 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800413 /*
414 * Create the network state trackers for Wi-Fi and mobile
415 * data. Maybe this could be done with a factory class,
416 * but it's not clear that it's worth it, given that
417 * the number of different network types is not going
418 * to change very often.
419 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700420 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700421 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700422 case ConnectivityManager.TYPE_WIFI:
Wink Savillee70c6f52010-12-03 12:01:38 -0800423 if (DBG) log("Starting Wifi Service.");
Wink Saville7fabfa22010-08-13 16:11:42 -0700424 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff25be0762010-07-28 09:35:20 -0700425 WifiService wifiService = new WifiService(context);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700426 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff25be0762010-07-28 09:35:20 -0700427 wifiService.checkAndStartWifi();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700428 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Saville7fabfa22010-08-13 16:11:42 -0700429 wst.startMonitoring(context, mHandler);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800430
Irfan Sheriff653e2a22010-06-07 09:03:04 -0700431 //TODO: as part of WWS refactor, create only when needed
Irfan Sheriff25be0762010-07-28 09:35:20 -0700432 mWifiWatchdogService = new WifiWatchdogService(context);
Irfan Sheriff653e2a22010-06-07 09:03:04 -0700433
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700434 break;
435 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700436 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700437 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700438 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700439 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800440 case ConnectivityManager.TYPE_DUMMY:
441 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700442 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800443 mNetTrackers[netType].startMonitoring(context, mHandler);
444 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800445 case ConnectivityManager.TYPE_BLUETOOTH:
446 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
447 mNetTrackers[netType].startMonitoring(context, mHandler);
448 break;
Benoit Goby6cec7f32010-12-22 14:29:40 -0800449 case ConnectivityManager.TYPE_ETHERNET:
450 mNetTrackers[netType] = EthernetDataTracker.getInstance();
451 mNetTrackers[netType].startMonitoring(context, mHandler);
452 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700453 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800454 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700455 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700456 continue;
457 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700458 mCurrentLinkProperties[netType] = null;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700459 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800460
Robert Greenwaltc0b6c602010-03-11 15:03:08 -0800461 mTethering = new Tethering(mContext, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700462 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700463 mTethering.getTetherableWifiRegexs().length != 0 ||
464 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700465 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800466
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700467 if (DBG) {
468 mInetLog = new ArrayList();
469 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700470
471 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
472 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800473
474 loadGlobalProxy();
Hung-ying Tyan4e723422011-01-19 16:48:38 +0800475
476 VpnManager.startVpnService(context);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800477 }
478
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700479
The Android Open Source Project28527d22009-03-03 19:31:44 -0800480 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700481 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800482 * @param preference the new preference
483 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700484 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800485 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700486
487 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800488 }
489
490 public int getNetworkPreference() {
491 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700492 int preference;
493 synchronized(this) {
494 preference = mNetworkPreference;
495 }
496 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800497 }
498
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700499 private void handleSetNetworkPreference(int preference) {
500 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700501 mNetConfigs[preference] != null &&
502 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700503 if (mNetworkPreference != preference) {
504 final ContentResolver cr = mContext.getContentResolver();
505 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
506 synchronized(this) {
507 mNetworkPreference = preference;
508 }
509 enforcePreference();
510 }
511 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800512 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700513
The Android Open Source Project28527d22009-03-03 19:31:44 -0800514 private int getPersistedNetworkPreference() {
515 final ContentResolver cr = mContext.getContentResolver();
516
517 final int networkPrefSetting = Settings.Secure
518 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
519 if (networkPrefSetting != -1) {
520 return networkPrefSetting;
521 }
522
523 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
524 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700525
The Android Open Source Project28527d22009-03-03 19:31:44 -0800526 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700527 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800528 * In this method, we only tear down a non-preferred network. Establishing
529 * a connection to the preferred network is taken care of when we handle
530 * the disconnect event from the non-preferred network
531 * (see {@link #handleDisconnect(NetworkInfo)}).
532 */
533 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700534 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800535 return;
536
Robert Greenwalt2034b912009-08-12 16:08:25 -0700537 if (!mNetTrackers[mNetworkPreference].isAvailable())
538 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800539
Robert Greenwalt2034b912009-08-12 16:08:25 -0700540 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700541 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700542 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700543 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800544 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700545 " in enforcePreference");
546 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700547 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800548 }
549 }
550 }
551
552 private boolean teardown(NetworkStateTracker netTracker) {
553 if (netTracker.teardown()) {
554 netTracker.setTeardownRequested(true);
555 return true;
556 } else {
557 return false;
558 }
559 }
560
561 /**
562 * Return NetworkInfo for the active (i.e., connected) network interface.
563 * It is assumed that at most one network is active at a time. If more
564 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700565 * @return the info for the active network, or {@code null} if none is
566 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800567 */
568 public NetworkInfo getActiveNetworkInfo() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700569 return getNetworkInfo(mActiveDefaultNetwork);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800570 }
571
572 public NetworkInfo getNetworkInfo(int networkType) {
573 enforceAccessPermission();
574 if (ConnectivityManager.isNetworkTypeValid(networkType)) {
575 NetworkStateTracker t = mNetTrackers[networkType];
576 if (t != null)
577 return t.getNetworkInfo();
578 }
579 return null;
580 }
581
582 public NetworkInfo[] getAllNetworkInfo() {
583 enforceAccessPermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700584 NetworkInfo[] result = new NetworkInfo[mNetworksDefined];
The Android Open Source Project28527d22009-03-03 19:31:44 -0800585 int i = 0;
586 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700587 if(t != null) result[i++] = t.getNetworkInfo();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800588 }
589 return result;
590 }
591
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700592 /**
593 * Return LinkProperties for the active (i.e., connected) default
594 * network interface. It is assumed that at most one default network
595 * is active at a time. If more than one is active, it is indeterminate
596 * which will be returned.
597 * @return the ip properties for the active network, or {@code null} if
598 * none is active
599 */
600 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700601 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700602 }
603
604 public LinkProperties getLinkProperties(int networkType) {
605 enforceAccessPermission();
606 if (ConnectivityManager.isNetworkTypeValid(networkType)) {
607 NetworkStateTracker t = mNetTrackers[networkType];
608 if (t != null) return t.getLinkProperties();
609 }
610 return null;
611 }
612
The Android Open Source Project28527d22009-03-03 19:31:44 -0800613 public boolean setRadios(boolean turnOn) {
614 boolean result = true;
615 enforceChangePermission();
616 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700617 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800618 }
619 return result;
620 }
621
622 public boolean setRadio(int netType, boolean turnOn) {
623 enforceChangePermission();
624 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
625 return false;
626 }
627 NetworkStateTracker tracker = mNetTrackers[netType];
628 return tracker != null && tracker.setRadio(turnOn);
629 }
630
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700631 /**
632 * Used to notice when the calling process dies so we can self-expire
633 *
634 * Also used to know if the process has cleaned up after itself when
635 * our auto-expire timer goes off. The timer has a link to an object.
636 *
637 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700638 private class FeatureUser implements IBinder.DeathRecipient {
639 int mNetworkType;
640 String mFeature;
641 IBinder mBinder;
642 int mPid;
643 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800644 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700645
646 FeatureUser(int type, String feature, IBinder binder) {
647 super();
648 mNetworkType = type;
649 mFeature = feature;
650 mBinder = binder;
651 mPid = getCallingPid();
652 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800653 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700654
Robert Greenwalt2034b912009-08-12 16:08:25 -0700655 try {
656 mBinder.linkToDeath(this, 0);
657 } catch (RemoteException e) {
658 binderDied();
659 }
660 }
661
662 void unlinkDeathRecipient() {
663 mBinder.unlinkToDeath(this, 0);
664 }
665
666 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800667 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800668 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
669 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700670 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700671 }
672
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700673 public void expire() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800674 log("ConnectivityService FeatureUser expire(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800675 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
676 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700677 stopUsingNetworkFeature(this, false);
678 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800679
680 public String toString() {
681 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
682 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
683 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700684 }
685
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700686 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700687 public int startUsingNetworkFeature(int networkType, String feature,
688 IBinder binder) {
689 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800690 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700691 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800692 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700693 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700694 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700695 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800696 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700697
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700698 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700699
700 // TODO - move this into the MobileDataStateTracker
701 int usedNetworkType = networkType;
702 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savilleb7c92c72011-03-12 14:52:01 -0800703 usedNetworkType = convertFeatureToNetworkType(feature);
704 if (usedNetworkType < 0) {
705 Slog.e(TAG, "Can't match any netTracker!");
706 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700707 }
708 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700709
710 if (mProtectedNetworks.contains(usedNetworkType)) {
711 enforceConnectivityInternalPermission();
712 }
713
Robert Greenwalt2034b912009-08-12 16:08:25 -0700714 NetworkStateTracker network = mNetTrackers[usedNetworkType];
715 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800716 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700717 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700718 NetworkStateTracker radio = mNetTrackers[networkType];
719 NetworkInfo ni = network.getNetworkInfo();
720
721 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800722 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800723 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
724 return Phone.APN_TYPE_NOT_AVAILABLE;
725 } else {
726 // else make the attempt anyway - probably giving REQUEST_STARTED below
727 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700728 }
729
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700730 synchronized(this) {
731 mFeatureUsers.add(f);
732 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
733 // this gets used for per-pid dns when connected
734 mNetRequestersPids[usedNetworkType].add(currentPid);
735 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700736 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700737
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700738 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
739
740 if (restoreTimer >= 0) {
741 mHandler.sendMessageDelayed(
742 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
743 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700744
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700745 if ((ni.isConnectedOrConnecting() == true) &&
746 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700747 if (ni.isConnected() == true) {
748 // add the pid-specific dns
Robert Greenwalt3afbead2010-07-23 15:46:26 -0700749 handleDnsConfigurationChange(networkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800750 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700751 return Phone.APN_ALREADY_ACTIVE;
752 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800753 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700754 return Phone.APN_REQUEST_STARTED;
755 }
756
757 // check if the radio in play can make another contact
758 // assume if cannot for now
759
Wink Savillee70c6f52010-12-03 12:01:38 -0800760 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700761 network.reconnect();
762 return Phone.APN_REQUEST_STARTED;
763 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800764 // need to remember this unsupported request so we respond appropriately on stop
765 synchronized(this) {
766 mFeatureUsers.add(f);
767 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
768 // this gets used for per-pid dns when connected
769 mNetRequestersPids[usedNetworkType].add(currentPid);
770 }
771 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700772 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700773 }
774 }
775 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800776 }
777
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700778 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800779 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700780 enforceChangePermission();
781
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700782 int pid = getCallingPid();
783 int uid = getCallingUid();
784
785 FeatureUser u = null;
786 boolean found = false;
787
788 synchronized(this) {
789 for (int i = 0; i < mFeatureUsers.size() ; i++) {
790 u = (FeatureUser)mFeatureUsers.get(i);
791 if (uid == u.mUid && pid == u.mPid &&
792 networkType == u.mNetworkType &&
793 TextUtils.equals(feature, u.mFeature)) {
794 found = true;
795 break;
796 }
797 }
798 }
799 if (found && u != null) {
800 // stop regardless of how many other time this proc had called start
801 return stopUsingNetworkFeature(u, true);
802 } else {
803 // none found!
Wink Savillee70c6f52010-12-03 12:01:38 -0800804 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700805 return 1;
806 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700807 }
808
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700809 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
810 int networkType = u.mNetworkType;
811 String feature = u.mFeature;
812 int pid = u.mPid;
813 int uid = u.mUid;
814
815 NetworkStateTracker tracker = null;
816 boolean callTeardown = false; // used to carry our decision outside of sync block
817
Robert Greenwalt2034b912009-08-12 16:08:25 -0700818 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800819 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700820 ": " + feature);
821 }
Robert Greenwalt28f43012009-10-06 17:52:40 -0700822
The Android Open Source Project28527d22009-03-03 19:31:44 -0800823 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
824 return -1;
825 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700826
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700827 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
828 // sync block
829 synchronized(this) {
830 // check if this process still has an outstanding start request
831 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800832 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700833 return 1;
834 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700835 u.unlinkDeathRecipient();
836 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
837 // If we care about duplicate requests, check for that here.
838 //
839 // This is done to support the extension of a request - the app
840 // can request we start the network feature again and renew the
841 // auto-shutoff delay. Normal "stop" calls from the app though
842 // do not pay attention to duplicate requests - in effect the
843 // API does not refcount and a single stop will counter multiple starts.
844 if (ignoreDups == false) {
845 for (int i = 0; i < mFeatureUsers.size() ; i++) {
846 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
847 if (x.mUid == u.mUid && x.mPid == u.mPid &&
848 x.mNetworkType == u.mNetworkType &&
849 TextUtils.equals(x.mFeature, u.mFeature)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800850 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700851 return 1;
852 }
853 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700854 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700855
856 // TODO - move to MobileDataStateTracker
857 int usedNetworkType = networkType;
858 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savilleb7c92c72011-03-12 14:52:01 -0800859 usedNetworkType = convertFeatureToNetworkType(feature);
860 if (usedNetworkType < 0) {
861 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700862 }
863 }
864 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700865 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800866 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700867 return -1;
868 }
869 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700870 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700871 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -0800872 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700873 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800874 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700875 "others still using it");
876 return 1;
877 }
878 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -0800879 } else {
880 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700881 }
882 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800883 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700884 if (callTeardown) {
885 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700886 return 1;
887 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -0700888 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700889 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800890 }
891
892 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700893 * @deprecated use requestRouteToHostAddress instead
894 *
The Android Open Source Project28527d22009-03-03 19:31:44 -0800895 * Ensure that a network route exists to deliver traffic to the specified
896 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700897 * @param networkType the type of the network over which traffic to the
898 * specified host is to be routed
899 * @param hostAddress the IP address of the host to which the route is
900 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -0800901 * @return {@code true} on success, {@code false} on failure
902 */
903 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700904 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
905
906 if (inetAddress == null) {
907 return false;
908 }
909
910 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
911 }
912
913 /**
914 * Ensure that a network route exists to deliver traffic to the specified
915 * host via the specified network interface.
916 * @param networkType the type of the network over which traffic to the
917 * specified host is to be routed
918 * @param hostAddress the IP address of the host to which the route is
919 * desired
920 * @return {@code true} on success, {@code false} on failure
921 */
922 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800923 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700924 if (mProtectedNetworks.contains(networkType)) {
925 enforceConnectivityInternalPermission();
926 }
927
The Android Open Source Project28527d22009-03-03 19:31:44 -0800928 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
929 return false;
930 }
931 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -0700932
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700933 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
934 tracker.isTeardownRequested()) {
Robert Greenwalt4666ed02009-09-10 15:06:20 -0700935 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800936 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700937 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -0700938 }
939 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800940 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700941 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700942 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700943 LinkProperties lp = tracker.getLinkProperties();
944 return addRoute(lp, RouteInfo.makeHostRoute(addr));
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700945 } catch (UnknownHostException e) {}
946 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700947 }
948
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700949 private boolean addRoute(LinkProperties p, RouteInfo r) {
950 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltbd492212011-05-06 17:10:53 -0700951 }
952
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700953 private boolean removeRoute(LinkProperties p, RouteInfo r) {
954 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
955 }
956
957 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
958 boolean doAdd) {
959 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
960
961 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
962 loge("Error adding route - too much recursion");
963 return false;
964 }
965
966 if (r.isHostRoute() == false) {
967 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
968 if (bestRoute != null) {
969 if (bestRoute.getGateway().equals(r.getGateway()) == false) {
970 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
971 } else {
972 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
973 }
974 if (!modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd)) return false;
975 }
976 }
977 if (doAdd) {
978 if (DBG) log("Adding " + r + " for interface " + ifaceName);
979 mAddedRoutes.add(r);
980 try {
981 mNetd.addRoute(ifaceName, r);
982 } catch (Exception e) {
983 // never crash - catch them all
984 loge("Exception trying to add a route: " + e);
985 return false;
986 }
987 } else {
988 // if we remove this one and there are no more like it, then refcount==0 and
989 // we can remove it from the table
990 mAddedRoutes.remove(r);
991 if (mAddedRoutes.contains(r) == false) {
992 if (DBG) log("Removing " + r + " for interface " + ifaceName);
993 try {
994 mNetd.removeRoute(ifaceName, r);
995 } catch (Exception e) {
996 // never crash - catch them all
997 loge("Exception trying to remove a route: " + e);
998 return false;
999 }
1000 } else {
1001 if (DBG) log("not removing " + r + " as it's still in use");
1002 }
1003 }
1004 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001005 }
1006
1007 /**
1008 * @see ConnectivityManager#getBackgroundDataSetting()
1009 */
1010 public boolean getBackgroundDataSetting() {
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001011 return mBackgroundDataEnabled.get();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001012 }
Robert Greenwalt0659da32009-07-16 17:21:39 -07001013
The Android Open Source Project28527d22009-03-03 19:31:44 -08001014 /**
1015 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1016 */
1017 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1018 mContext.enforceCallingOrSelfPermission(
1019 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1020 "ConnectivityService");
Robert Greenwalt0659da32009-07-16 17:21:39 -07001021
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001022 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1023
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001024 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1025 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1026 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001027
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001028 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwalt0ffdef12011-02-25 13:44:09 -08001029 Settings.Secure.putInt(mContext.getContentResolver(),
1030 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1031 Intent broadcast = new Intent(
1032 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1033 mContext.sendBroadcast(broadcast);
Robert Greenwalt0659da32009-07-16 17:21:39 -07001034 }
1035
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001036 /**
1037 * @see ConnectivityManager#getMobileDataEnabled()
1038 */
1039 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001040 // TODO: This detail should probably be in DataConnectionTracker's
1041 // which is where we store the value and maybe make this
1042 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001043 enforceAccessPermission();
1044 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1045 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savillee70c6f52010-12-03 12:01:38 -08001046 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001047 return retVal;
1048 }
1049
Robert Greenwalt34848c02011-03-25 13:09:25 -07001050 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001051 enforceConnectivityInternalPermission();
1052
Robert Greenwalt34848c02011-03-25 13:09:25 -07001053 if (DBG) {
1054 log("setDataDependency(" + networkType + ", " + met + ")");
1055 }
1056 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1057 (met ? ENABLED : DISABLED), networkType));
1058 }
1059
1060 private void handleSetDependencyMet(int networkType, boolean met) {
1061 if (mNetTrackers[networkType] != null) {
1062 if (DBG) {
1063 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1064 }
1065 mNetTrackers[networkType].setDependencyMet(met);
1066 }
1067 }
1068
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001069 /**
1070 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1071 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001072 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001073 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001074 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001075
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001076 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001077 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001078 }
1079
1080 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001081 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1082 if (DBG) {
1083 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001084 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001085 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001086 }
1087 }
1088
The Android Open Source Project28527d22009-03-03 19:31:44 -08001089 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001090 mContext.enforceCallingOrSelfPermission(
1091 android.Manifest.permission.ACCESS_NETWORK_STATE,
1092 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001093 }
1094
1095 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001096 mContext.enforceCallingOrSelfPermission(
1097 android.Manifest.permission.CHANGE_NETWORK_STATE,
1098 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001099 }
1100
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001101 // TODO Make this a special check when it goes public
1102 private void enforceTetherChangePermission() {
1103 mContext.enforceCallingOrSelfPermission(
1104 android.Manifest.permission.CHANGE_NETWORK_STATE,
1105 "ConnectivityService");
1106 }
1107
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001108 private void enforceTetherAccessPermission() {
1109 mContext.enforceCallingOrSelfPermission(
1110 android.Manifest.permission.ACCESS_NETWORK_STATE,
1111 "ConnectivityService");
1112 }
1113
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001114 private void enforceConnectivityInternalPermission() {
1115 mContext.enforceCallingOrSelfPermission(
1116 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1117 "ConnectivityService");
1118 }
1119
The Android Open Source Project28527d22009-03-03 19:31:44 -08001120 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001121 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1122 * network, we ignore it. If it is for the active network, we send out a
1123 * broadcast. But first, we check whether it might be possible to connect
1124 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001125 * @param info the {@code NetworkInfo} for the network
1126 */
1127 private void handleDisconnect(NetworkInfo info) {
1128
Robert Greenwalt2034b912009-08-12 16:08:25 -07001129 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001130
Robert Greenwalt2034b912009-08-12 16:08:25 -07001131 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001132 /*
1133 * If the disconnected network is not the active one, then don't report
1134 * this as a loss of connectivity. What probably happened is that we're
1135 * getting the disconnect for a network that we explicitly disabled
1136 * in accordance with network preference policies.
1137 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001138 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001139 List pids = mNetRequestersPids[prevNetType];
1140 for (int i = 0; i<pids.size(); i++) {
1141 Integer pid = (Integer)pids.get(i);
1142 // will remove them because the net's no longer connected
1143 // need to do this now as only now do we know the pids and
1144 // can properly null things that are no longer referenced.
1145 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001146 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001147 }
1148
The Android Open Source Project28527d22009-03-03 19:31:44 -08001149 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1150 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1151 if (info.isFailover()) {
1152 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1153 info.setFailover(false);
1154 }
1155 if (info.getReason() != null) {
1156 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1157 }
1158 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001159 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1160 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001161 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001162
Robert Greenwalt34848c02011-03-25 13:09:25 -07001163 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001164 tryFailover(prevNetType);
1165 if (mActiveDefaultNetwork != -1) {
1166 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001167 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1168 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001169 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001170 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1171 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001172 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001173 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001174
1175 // Reset interface if no other connections are using the same interface
1176 boolean doReset = true;
1177 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1178 if (linkProperties != null) {
1179 String oldIface = linkProperties.getInterfaceName();
1180 if (TextUtils.isEmpty(oldIface) == false) {
1181 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1182 if (networkStateTracker == null) continue;
1183 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1184 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1185 LinkProperties l = networkStateTracker.getLinkProperties();
1186 if (l == null) continue;
1187 if (oldIface.equals(l.getInterfaceName())) {
1188 doReset = false;
1189 break;
1190 }
1191 }
1192 }
1193 }
1194 }
1195
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001196 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001197 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001198
1199 sendStickyBroadcast(intent);
1200 /*
1201 * If the failover network is already connected, then immediately send
1202 * out a followup broadcast indicating successful failover
1203 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001204 if (mActiveDefaultNetwork != -1) {
1205 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001206 }
1207 }
1208
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001209 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001210 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001211 * If this is a default network, check if other defaults are available.
1212 * Try to reconnect on all available and let them hash it out when
1213 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001214 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001215 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001216 if (mActiveDefaultNetwork == prevNetType) {
1217 mActiveDefaultNetwork = -1;
1218 }
1219
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001220 // don't signal a reconnect for anything lower or equal priority than our
1221 // current connected default
1222 // TODO - don't filter by priority now - nice optimization but risky
1223// int currentPriority = -1;
1224// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001225// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001226// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001227 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001228 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001229 if (mNetConfigs[checkType] == null) continue;
1230 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001231
1232// Enabling the isAvailable() optimization caused mobile to not get
1233// selected if it was in the middle of error handling. Specifically
1234// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1235// would not be available and we wouldn't get connected to anything.
1236// So removing the isAvailable() optimization below for now. TODO: This
1237// optimization should work and we need to investigate why it doesn't work.
1238// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1239// complete before it is really complete.
1240// if (!mNetTrackers[checkType].isAvailable()) continue;
1241
Robert Greenwalt34848c02011-03-25 13:09:25 -07001242// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001243
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001244 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1245 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1246 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1247 checkInfo.setFailover(true);
1248 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001249 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001250 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001251 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001252 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001253 }
1254
1255 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001256 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1257 }
1258
1259 private void sendInetConditionBroadcast(NetworkInfo info) {
1260 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1261 }
1262
1263 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1264 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001265 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1266 if (info.isFailover()) {
1267 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1268 info.setFailover(false);
1269 }
1270 if (info.getReason() != null) {
1271 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1272 }
1273 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001274 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1275 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001276 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001277 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001278 sendStickyBroadcast(intent);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001279 }
1280
1281 /**
1282 * Called when an attempt to fail over to another network has failed.
1283 * @param info the {@link NetworkInfo} for the failed network
1284 */
1285 private void handleConnectionFailure(NetworkInfo info) {
1286 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001287
Robert Greenwalt2034b912009-08-12 16:08:25 -07001288 String reason = info.getReason();
1289 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001290
Robert Greenwalte981bc52010-10-08 16:35:52 -07001291 String reasonText;
1292 if (reason == null) {
1293 reasonText = ".";
1294 } else {
1295 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001296 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001297 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001298
1299 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1300 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1301 if (getActiveNetworkInfo() == null) {
1302 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1303 }
1304 if (reason != null) {
1305 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1306 }
1307 if (extraInfo != null) {
1308 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1309 }
1310 if (info.isFailover()) {
1311 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1312 info.setFailover(false);
1313 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001314
Robert Greenwalt34848c02011-03-25 13:09:25 -07001315 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001316 tryFailover(info.getType());
1317 if (mActiveDefaultNetwork != -1) {
1318 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001319 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1320 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001321 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001322 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1323 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001324 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001325
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001326 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001327 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001328 /*
1329 * If the failover network is already connected, then immediately send
1330 * out a followup broadcast indicating successful failover
1331 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001332 if (mActiveDefaultNetwork != -1) {
1333 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001334 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001335 }
1336
1337 private void sendStickyBroadcast(Intent intent) {
1338 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001339 if (!mSystemReady) {
1340 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001341 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001342 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1343 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001344 }
1345 }
1346
1347 void systemReady() {
Robert Greenwalt355205c2011-05-10 15:05:02 -07001348 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1349 mNetd = INetworkManagementService.Stub.asInterface(b);
1350
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001351 synchronized(this) {
1352 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001353 if (mInitialBroadcast != null) {
1354 mContext.sendStickyBroadcast(mInitialBroadcast);
1355 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001356 }
1357 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001358 // load the global proxy at startup
1359 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001360 }
1361
1362 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001363 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001364
1365 // snapshot isFailover, because sendConnectedBroadcast() resets it
1366 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001367 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001368
Robert Greenwalt2034b912009-08-12 16:08:25 -07001369 // if this is a default net and other default is running
1370 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001371 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001372 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1373 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001374 mNetConfigs[mActiveDefaultNetwork].priority >
1375 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001376 mNetworkPreference == mActiveDefaultNetwork) {
1377 // don't accept this one
Wink Savillee70c6f52010-12-03 12:01:38 -08001378 if (DBG) {
1379 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001380 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001381 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001382 teardown(thisNet);
1383 return;
1384 } else {
1385 // tear down the other
1386 NetworkStateTracker otherNet =
1387 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001388 if (DBG) {
1389 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001390 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001391 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001392 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001393 loge("Network declined teardown request");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001394 return;
1395 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001396 }
1397 }
1398 synchronized (ConnectivityService.this) {
1399 // have a new default network, release the transition wakelock in a second
1400 // if it's held. The second pause is to allow apps to reconnect over the
1401 // new network
1402 if (mNetTransitionWakeLock.isHeld()) {
1403 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001404 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001405 mNetTransitionWakeLockSerialNumber, 0),
1406 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001407 }
1408 }
1409 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001410 // this will cause us to come up initially as unconnected and switching
1411 // to connected after our normal pause unless somebody reports us as reall
1412 // disconnected
1413 mDefaultInetConditionPublished = 0;
1414 mDefaultConnectionSequence++;
1415 mInetConditionChangeInFlight = false;
1416 // Don't do this - if we never sign in stay, grey
1417 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001418 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001419 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001420 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001421 handleConnectivityChange(type, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001422 sendConnectedBroadcast(info);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001423 }
1424
The Android Open Source Project28527d22009-03-03 19:31:44 -08001425 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001426 * After a change in the connectivity state of a network. We're mainly
1427 * concerned with making sure that the list of DNS servers is set up
1428 * according to which networks are connected, and ensuring that the
1429 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001430 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001431 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001432 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1433
The Android Open Source Project28527d22009-03-03 19:31:44 -08001434 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001435 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001436 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001437 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001438 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001439
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001440 LinkProperties curLp = mCurrentLinkProperties[netType];
1441 LinkProperties newLp = null;
1442
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001443 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001444 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001445 if (VDBG) {
1446 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1447 " doReset=" + doReset + " resetMask=" + resetMask +
1448 "\n curLp=" + curLp +
1449 "\n newLp=" + newLp);
1450 }
1451
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001452 if (curLp != null) {
1453 if (curLp.isIdenticalInterfaceName(newLp)) {
1454 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1455 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1456 for (LinkAddress linkAddr : car.removed) {
1457 if (linkAddr.getAddress() instanceof Inet4Address) {
1458 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1459 }
1460 if (linkAddr.getAddress() instanceof Inet6Address) {
1461 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1462 }
Wink Saville051a6642011-07-13 13:44:13 -07001463 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001464 if (DBG) {
1465 log("handleConnectivityChange: addresses changed" +
1466 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1467 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001468 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001469 } else {
1470 if (DBG) {
1471 log("handleConnectivityChange: address are the same reset per doReset" +
1472 " linkProperty[" + netType + "]:" +
1473 " resetMask=" + resetMask);
1474 }
Wink Saville051a6642011-07-13 13:44:13 -07001475 }
1476 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001477 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
1478 log("handleConnectivityChange: interface not not equivalent reset both" +
1479 " linkProperty[" + netType + "]:" +
1480 " resetMask=" + resetMask);
Wink Saville051a6642011-07-13 13:44:13 -07001481 }
Wink Saville051a6642011-07-13 13:44:13 -07001482 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001483 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001484 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001485 }
1486 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001487 if (VDBG) {
1488 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1489 " doReset=" + doReset + " resetMask=" + resetMask +
1490 "\n curLp=" + curLp +
1491 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001492 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001493 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001494 mCurrentLinkProperties[netType] = newLp;
1495 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001496
Wink Saville051a6642011-07-13 13:44:13 -07001497 if (doReset || resetMask != 0) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001498 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1499 if (linkProperties != null) {
1500 String iface = linkProperties.getInterfaceName();
1501 if (TextUtils.isEmpty(iface) == false) {
Wink Saville051a6642011-07-13 13:44:13 -07001502 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1503 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001504 }
1505 }
1506 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001507
1508 // TODO: Temporary notifying upstread change to Tethering.
1509 // @see bug/4455071
1510 /** Notify TetheringService if interface name has been changed. */
1511 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1512 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1513 if (isTetheringSupported()) {
1514 mTethering.handleTetherIfaceChange();
1515 }
1516 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001517 }
1518
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001519 /**
1520 * Add and remove routes using the old properties (null if not previously connected),
1521 * new properties (null if becoming disconnected). May even be double null, which
1522 * is a noop.
1523 * Uses isLinkDefault to determine if default routes should be set or conversely if
1524 * host routes should be set to the dns servers
1525 */
1526 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1527 Collection<RouteInfo> routesToAdd = null;
1528 CompareResult<InetAddress> dnsDiff = null;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001529
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001530 if (curLp != null) {
1531 // check for the delta between the current set and the new
1532 CompareResult<RouteInfo> routeDiff = curLp.compareRoutes(newLp);
1533 dnsDiff = curLp.compareDnses(newLp);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001534
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001535 for (RouteInfo r : routeDiff.removed) {
1536 if (isLinkDefault || ! r.isDefaultRoute()) {
1537 removeRoute(curLp, r);
Robert Greenwalt355205c2011-05-10 15:05:02 -07001538 }
1539 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001540 routesToAdd = routeDiff.added;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001541 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001542
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001543 if (newLp != null) {
1544 // if we didn't get a diff from cur -> new, then just use the new
1545 if (routesToAdd == null) {
1546 routesToAdd = newLp.getRoutes();
1547 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001548
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001549 for (RouteInfo r : routesToAdd) {
1550 if (isLinkDefault || ! r.isDefaultRoute()) {
1551 addRoute(newLp, r);
1552 }
1553 }
1554 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001555
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001556 if (!isLinkDefault) {
1557 // handle DNS routes
1558 Collection<InetAddress> dnsToAdd = null;
1559 if (dnsDiff != null) {
1560 dnsToAdd = dnsDiff.added;
1561 for (InetAddress dnsAddress : dnsDiff.removed) {
1562 removeRoute(curLp, RouteInfo.makeHostRoute(dnsAddress));
1563 }
1564 }
1565 if (newLp != null) {
1566 if (dnsToAdd == null) {
1567 dnsToAdd = newLp.getDnses();
1568 }
1569 for(InetAddress dnsAddress : dnsToAdd) {
1570 addRoute(newLp, RouteInfo.makeHostRoute(dnsAddress));
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001571 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001572 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001573 }
1574 }
1575
1576
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001577 /**
1578 * Reads the network specific TCP buffer sizes from SystemProperties
1579 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1580 * wide use
1581 */
1582 public void updateNetworkSettings(NetworkStateTracker nt) {
1583 String key = nt.getTcpBufferSizesPropName();
1584 String bufferSizes = SystemProperties.get(key);
1585
1586 if (bufferSizes.length() == 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001587 loge(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001588
1589 // Setting to default values so we won't be stuck to previous values
1590 key = "net.tcp.buffersize.default";
1591 bufferSizes = SystemProperties.get(key);
1592 }
1593
1594 // Set values in kernel
1595 if (bufferSizes.length() != 0) {
1596 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001597 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001598 + "] which comes from [" + key + "]");
1599 }
1600 setBufferSize(bufferSizes);
1601 }
1602 }
1603
1604 /**
1605 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1606 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1607 *
1608 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1609 * writeMin, writeInitial, writeMax"
1610 */
1611 private void setBufferSize(String bufferSizes) {
1612 try {
1613 String[] values = bufferSizes.split(",");
1614
1615 if (values.length == 6) {
1616 final String prefix = "/sys/kernel/ipv4/tcp_";
1617 stringToFile(prefix + "rmem_min", values[0]);
1618 stringToFile(prefix + "rmem_def", values[1]);
1619 stringToFile(prefix + "rmem_max", values[2]);
1620 stringToFile(prefix + "wmem_min", values[3]);
1621 stringToFile(prefix + "wmem_def", values[4]);
1622 stringToFile(prefix + "wmem_max", values[5]);
1623 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001624 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001625 }
1626 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001627 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001628 }
1629 }
1630
1631 /**
1632 * Writes string to file. Basically same as "echo -n $string > $filename"
1633 *
1634 * @param filename
1635 * @param string
1636 * @throws IOException
1637 */
1638 private void stringToFile(String filename, String string) throws IOException {
1639 FileWriter out = new FileWriter(filename);
1640 try {
1641 out.write(string);
1642 } finally {
1643 out.close();
1644 }
1645 }
1646
1647
Robert Greenwalt2034b912009-08-12 16:08:25 -07001648 /**
1649 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1650 * on the highest priority active net which this process requested.
1651 * If there aren't any, clear it out
1652 */
1653 private void reassessPidDns(int myPid, boolean doBump)
1654 {
Wink Savillee70c6f52010-12-03 12:01:38 -08001655 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001656 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001657 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001658 continue;
1659 }
1660 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001661 if (nt.getNetworkInfo().isConnected() &&
1662 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001663 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001664 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001665 List pids = mNetRequestersPids[i];
1666 for (int j=0; j<pids.size(); j++) {
1667 Integer pid = (Integer)pids.get(j);
1668 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001669 Collection<InetAddress> dnses = p.getDnses();
1670 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001671 if (doBump) {
1672 bumpDns();
1673 }
1674 return;
1675 }
1676 }
1677 }
1678 }
1679 // nothing found - delete
1680 for (int i = 1; ; i++) {
1681 String prop = "net.dns" + i + "." + myPid;
1682 if (SystemProperties.get(prop).length() == 0) {
1683 if (doBump) {
1684 bumpDns();
1685 }
1686 return;
1687 }
1688 SystemProperties.set(prop, "");
1689 }
1690 }
1691
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001692 // return true if results in a change
1693 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001694 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001695 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001696 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001697 String dnsString = dns.getHostAddress();
1698 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1699 changed = true;
1700 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1701 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001702 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001703 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001704 }
1705
1706 private void bumpDns() {
1707 /*
1708 * Bump the property that tells the name resolver library to reread
1709 * the DNS server list from the properties.
1710 */
1711 String propVal = SystemProperties.get("net.dnschange");
1712 int n = 0;
1713 if (propVal.length() != 0) {
1714 try {
1715 n = Integer.parseInt(propVal);
1716 } catch (NumberFormatException e) {}
1717 }
1718 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001719 /*
1720 * Tell the VMs to toss their DNS caches
1721 */
1722 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1723 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08001724 /*
1725 * Connectivity events can happen before boot has completed ...
1726 */
1727 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07001728 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001729 }
1730
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001731 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001732 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001733 NetworkStateTracker nt = mNetTrackers[netType];
1734 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001735 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001736 if (p == null) return;
1737 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001738 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001739 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001740 int j = 1;
Robert Greenwalt94daa182010-09-01 11:34:05 -07001741 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001742 String dnsString = mDefaultDns.getHostAddress();
1743 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1744 if (DBG) {
1745 log("no dns provided - using " + dnsString);
1746 }
1747 changed = true;
1748 SystemProperties.set("net.dns1", dnsString);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001749 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001750 j++;
1751 } else {
1752 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001753 String dnsString = dns.getHostAddress();
1754 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1755 j++;
1756 continue;
1757 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001758 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001759 log("adding dns " + dns + " for " +
Robert Greenwalt94daa182010-09-01 11:34:05 -07001760 nt.getNetworkInfo().getTypeName());
1761 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001762 changed = true;
1763 SystemProperties.set("net.dns" + j++, dnsString);
Robert Greenwalt94daa182010-09-01 11:34:05 -07001764 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001765 }
1766 for (int k=j ; k<mNumDnsEntries; k++) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001767 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1768 if (DBG) log("erasing net.dns" + k);
1769 changed = true;
1770 SystemProperties.set("net.dns" + k, "");
1771 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001772 }
1773 mNumDnsEntries = j;
1774 } else {
1775 // set per-pid dns for attached secondary nets
1776 List pids = mNetRequestersPids[netType];
1777 for (int y=0; y< pids.size(); y++) {
1778 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001779 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001780 }
1781 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001782 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001783 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001784 }
1785
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001786 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001787 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1788 NETWORK_RESTORE_DELAY_PROP_NAME);
1789 if(restoreDefaultNetworkDelayStr != null &&
1790 restoreDefaultNetworkDelayStr.length() != 0) {
1791 try {
1792 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1793 } catch (NumberFormatException e) {
1794 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001795 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001796 // if the system property isn't set, use the value for the apn type
1797 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1798
1799 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1800 (mNetConfigs[networkType] != null)) {
1801 ret = mNetConfigs[networkType].restoreTime;
1802 }
1803 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001804 }
1805
1806 @Override
1807 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001808 if (mContext.checkCallingOrSelfPermission(
1809 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001810 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001811 pw.println("Permission Denial: can't dump ConnectivityService " +
1812 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1813 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001814 return;
1815 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001816 pw.println();
1817 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001818 if (nst != null) {
1819 if (nst.getNetworkInfo().isConnected()) {
1820 pw.println("Active network: " + nst.getNetworkInfo().
1821 getTypeName());
1822 }
1823 pw.println(nst.getNetworkInfo());
1824 pw.println(nst);
1825 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001826 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001827 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001828
1829 pw.println("Network Requester Pids:");
1830 for (int net : mPriorityList) {
1831 String pidString = net + ": ";
1832 for (Object pid : mNetRequestersPids[net]) {
1833 pidString = pidString + pid.toString() + ", ";
1834 }
1835 pw.println(pidString);
1836 }
1837 pw.println();
1838
1839 pw.println("FeatureUsers:");
1840 for (Object requester : mFeatureUsers) {
1841 pw.println(requester.toString());
1842 }
1843 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001844
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001845 synchronized (this) {
1846 pw.println("NetworkTranstionWakeLock is currently " +
1847 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1848 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1849 }
1850 pw.println();
1851
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001852 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07001853
1854 if (mInetLog != null) {
1855 pw.println();
1856 pw.println("Inet condition reports:");
1857 for(int i = 0; i < mInetLog.size(); i++) {
1858 pw.println(mInetLog.get(i));
1859 }
1860 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001861 }
1862
Robert Greenwalt2034b912009-08-12 16:08:25 -07001863 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001864 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07001865 public MyHandler(Looper looper) {
1866 super(looper);
1867 }
1868
The Android Open Source Project28527d22009-03-03 19:31:44 -08001869 @Override
1870 public void handleMessage(Message msg) {
1871 NetworkInfo info;
1872 switch (msg.what) {
1873 case NetworkStateTracker.EVENT_STATE_CHANGED:
1874 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08001875 int type = info.getType();
1876 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08001877
Wink Savillee70c6f52010-12-03 12:01:38 -08001878 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07001879 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08001880 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001881
1882 // Connectivity state changed:
1883 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07001884 // [12-9] Network subtype (for mobile network, as defined
1885 // by TelephonyManager)
1886 // [8-3] Detailed state ordinal (as defined by
1887 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001888 // [2-0] Network type (as defined by ConnectivityManager)
1889 int eventLogParam = (info.getType() & 0x7) |
1890 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1891 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08001892 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07001893 eventLogParam);
1894
1895 if (info.getDetailedState() ==
1896 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001897 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001898 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001899 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001900 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001901 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001902 // the logic here is, handle SUSPENDED the same as
1903 // DISCONNECTED. The only difference being we are
1904 // broadcasting an intent with NetworkInfo that's
1905 // suspended. This allows the applications an
1906 // opportunity to handle DISCONNECTED and SUSPENDED
1907 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001908 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001909 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001910 handleConnect(info);
1911 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001912 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001913 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001914 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001915 // TODO: Temporary allowing network configuration
1916 // change not resetting sockets.
1917 // @see bug/4455071
1918 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001919 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001920 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001921 String causedBy = null;
1922 synchronized (ConnectivityService.this) {
1923 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
1924 mNetTransitionWakeLock.isHeld()) {
1925 mNetTransitionWakeLock.release();
1926 causedBy = mNetTransitionWakeLockCausedBy;
1927 }
1928 }
1929 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001930 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001931 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07001932 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001933 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001934 FeatureUser u = (FeatureUser)msg.obj;
1935 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07001936 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001937 case EVENT_INET_CONDITION_CHANGE:
1938 {
1939 int netType = msg.arg1;
1940 int condition = msg.arg2;
1941 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001942 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001943 }
1944 case EVENT_INET_CONDITION_HOLD_END:
1945 {
1946 int netType = msg.arg1;
1947 int sequence = msg.arg2;
1948 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07001949 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001950 }
1951 case EVENT_SET_NETWORK_PREFERENCE:
1952 {
1953 int preference = msg.arg1;
1954 handleSetNetworkPreference(preference);
1955 break;
1956 }
1957 case EVENT_SET_BACKGROUND_DATA:
1958 {
1959 boolean enabled = (msg.arg1 == ENABLED);
1960 handleSetBackgroundData(enabled);
1961 break;
1962 }
1963 case EVENT_SET_MOBILE_DATA:
1964 {
1965 boolean enabled = (msg.arg1 == ENABLED);
1966 handleSetMobileData(enabled);
1967 break;
1968 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001969 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
1970 {
1971 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07001972 break;
1973 }
1974 case EVENT_SET_DEPENDENCY_MET:
1975 {
1976 boolean met = (msg.arg1 == ENABLED);
1977 handleSetDependencyMet(msg.arg2, met);
1978 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001979 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001980 }
1981 }
1982 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001983
1984 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08001985 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001986 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08001987
1988 if (isTetheringSupported()) {
1989 return mTethering.tether(iface);
1990 } else {
1991 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1992 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001993 }
1994
1995 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08001996 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001997 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08001998
1999 if (isTetheringSupported()) {
2000 return mTethering.untether(iface);
2001 } else {
2002 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2003 }
2004 }
2005
2006 // javadoc from interface
2007 public int getLastTetherError(String iface) {
2008 enforceTetherAccessPermission();
2009
2010 if (isTetheringSupported()) {
2011 return mTethering.getLastTetherError(iface);
2012 } else {
2013 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2014 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002015 }
2016
2017 // TODO - proper iface API for selection by property, inspection, etc
2018 public String[] getTetherableUsbRegexs() {
2019 enforceTetherAccessPermission();
2020 if (isTetheringSupported()) {
2021 return mTethering.getTetherableUsbRegexs();
2022 } else {
2023 return new String[0];
2024 }
2025 }
2026
2027 public String[] getTetherableWifiRegexs() {
2028 enforceTetherAccessPermission();
2029 if (isTetheringSupported()) {
2030 return mTethering.getTetherableWifiRegexs();
2031 } else {
2032 return new String[0];
2033 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002034 }
2035
Danica Chang96567052010-08-11 14:54:43 -07002036 public String[] getTetherableBluetoothRegexs() {
2037 enforceTetherAccessPermission();
2038 if (isTetheringSupported()) {
2039 return mTethering.getTetherableBluetoothRegexs();
2040 } else {
2041 return new String[0];
2042 }
2043 }
2044
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002045 // TODO - move iface listing, queries, etc to new module
2046 // javadoc from interface
2047 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002048 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002049 return mTethering.getTetherableIfaces();
2050 }
2051
2052 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002053 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002054 return mTethering.getTetheredIfaces();
2055 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002056
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002057 public String[] getTetheringErroredIfaces() {
2058 enforceTetherAccessPermission();
2059 return mTethering.getErroredIfaces();
2060 }
2061
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002062 // if ro.tether.denied = true we default to no tethering
2063 // gservices could set the secure setting to 1 though to enable it on a build where it
2064 // had previously been turned off.
2065 public boolean isTetheringSupported() {
2066 enforceTetherAccessPermission();
2067 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002068 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2069 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2070 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002071 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002072
2073 // An API NetworkStateTrackers can call when they lose their network.
2074 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2075 // whichever happens first. The timer is started by the first caller and not
2076 // restarted by subsequent callers.
2077 public void requestNetworkTransitionWakelock(String forWhom) {
2078 enforceConnectivityInternalPermission();
2079 synchronized (this) {
2080 if (mNetTransitionWakeLock.isHeld()) return;
2081 mNetTransitionWakeLockSerialNumber++;
2082 mNetTransitionWakeLock.acquire();
2083 mNetTransitionWakeLockCausedBy = forWhom;
2084 }
2085 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002086 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002087 mNetTransitionWakeLockSerialNumber, 0),
2088 mNetTransitionWakeLockTimeout);
2089 return;
2090 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002091
Robert Greenwalt986c7412010-09-08 15:24:47 -07002092 // 100 percent is full good, 0 is full bad.
2093 public void reportInetCondition(int networkType, int percentage) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002094 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002095 mContext.enforceCallingOrSelfPermission(
2096 android.Manifest.permission.STATUS_BAR,
2097 "ConnectivityService");
2098
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002099 if (DBG) {
2100 int pid = getCallingPid();
2101 int uid = getCallingUid();
2102 String s = pid + "(" + uid + ") reports inet is " +
2103 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2104 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2105 mInetLog.add(s);
2106 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2107 mInetLog.remove(0);
2108 }
2109 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002110 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002111 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2112 }
2113
2114 private void handleInetConditionChange(int netType, int condition) {
2115 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002116 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002117 netType + ", condition=" + condition +
2118 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2119 }
2120 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002121 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002122 return;
2123 }
2124 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002125 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002126 return;
2127 }
2128 mDefaultInetCondition = condition;
2129 int delay;
2130 if (mInetConditionChangeInFlight == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002131 if (DBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002132 // setup a new hold to debounce this
2133 if (mDefaultInetCondition > 50) {
2134 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2135 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2136 } else {
2137 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2138 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2139 }
2140 mInetConditionChangeInFlight = true;
2141 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2142 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2143 } else {
2144 // we've set the new condition, when this hold ends that will get
2145 // picked up
Wink Savillee70c6f52010-12-03 12:01:38 -08002146 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002147 }
2148 }
2149
2150 private void handleInetConditionHoldEnd(int netType, int sequence) {
2151 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002152 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002153 ", condition =" + mDefaultInetCondition +
2154 ", published condition =" + mDefaultInetConditionPublished);
2155 }
2156 mInetConditionChangeInFlight = false;
2157
2158 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002159 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002160 return;
2161 }
2162 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002163 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002164 return;
2165 }
2166 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002167 if (DBG) log("no change in condition - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002168 return;
2169 }
2170 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2171 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002172 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002173 return;
2174 }
2175 mDefaultInetConditionPublished = mDefaultInetCondition;
2176 sendInetConditionBroadcast(networkInfo);
2177 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002178 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002179
2180 public synchronized ProxyProperties getProxy() {
2181 if (mGlobalProxy != null) return mGlobalProxy;
2182 if (mDefaultProxy != null) return mDefaultProxy;
2183 return null;
2184 }
2185
2186 public void setGlobalProxy(ProxyProperties proxyProperties) {
2187 enforceChangePermission();
2188 synchronized (mGlobalProxyLock) {
2189 if (proxyProperties == mGlobalProxy) return;
2190 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2191 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2192
2193 String host = "";
2194 int port = 0;
2195 String exclList = "";
2196 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2197 mGlobalProxy = new ProxyProperties(proxyProperties);
2198 host = mGlobalProxy.getHost();
2199 port = mGlobalProxy.getPort();
2200 exclList = mGlobalProxy.getExclusionList();
2201 } else {
2202 mGlobalProxy = null;
2203 }
2204 ContentResolver res = mContext.getContentResolver();
2205 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2206 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002207 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002208 exclList);
2209 }
2210
2211 if (mGlobalProxy == null) {
2212 proxyProperties = mDefaultProxy;
2213 }
2214 sendProxyBroadcast(proxyProperties);
2215 }
2216
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002217 private void loadGlobalProxy() {
2218 ContentResolver res = mContext.getContentResolver();
2219 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2220 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2221 String exclList = Settings.Secure.getString(res,
2222 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2223 if (!TextUtils.isEmpty(host)) {
2224 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2225 synchronized (mGlobalProxyLock) {
2226 mGlobalProxy = proxyProperties;
2227 }
2228 }
2229 }
2230
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002231 public ProxyProperties getGlobalProxy() {
2232 synchronized (mGlobalProxyLock) {
2233 return mGlobalProxy;
2234 }
2235 }
2236
2237 private void handleApplyDefaultProxy(int type) {
2238 // check if new default - push it out to all VM if so
2239 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2240 synchronized (this) {
2241 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2242 if (mDefaultProxy == proxy) return;
2243 if (!TextUtils.isEmpty(proxy.getHost())) {
2244 mDefaultProxy = proxy;
2245 } else {
2246 mDefaultProxy = null;
2247 }
2248 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002249 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002250 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2251 if (mGlobalProxy != null) return;
2252 sendProxyBroadcast(proxy);
2253 }
2254
2255 private void handleDeprecatedGlobalHttpProxy() {
2256 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2257 Settings.Secure.HTTP_PROXY);
2258 if (!TextUtils.isEmpty(proxy)) {
2259 String data[] = proxy.split(":");
2260 String proxyHost = data[0];
2261 int proxyPort = 8080;
2262 if (data.length > 1) {
2263 try {
2264 proxyPort = Integer.parseInt(data[1]);
2265 } catch (NumberFormatException e) {
2266 return;
2267 }
2268 }
2269 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2270 setGlobalProxy(p);
2271 }
2272 }
2273
2274 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002275 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savillee70c6f52010-12-03 12:01:38 -08002276 log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002277 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002278 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2279 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002280 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002281 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002282 }
2283
2284 private static class SettingsObserver extends ContentObserver {
2285 private int mWhat;
2286 private Handler mHandler;
2287 SettingsObserver(Handler handler, int what) {
2288 super(handler);
2289 mHandler = handler;
2290 mWhat = what;
2291 }
2292
2293 void observe(Context context) {
2294 ContentResolver resolver = context.getContentResolver();
2295 resolver.registerContentObserver(Settings.Secure.getUriFor(
2296 Settings.Secure.HTTP_PROXY), false, this);
2297 }
2298
2299 @Override
2300 public void onChange(boolean selfChange) {
2301 mHandler.obtainMessage(mWhat).sendToTarget();
2302 }
2303 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002304
2305 private void log(String s) {
2306 Slog.d(TAG, s);
2307 }
2308
2309 private void loge(String s) {
2310 Slog.e(TAG, s);
2311 }
Wink Savilleb7c92c72011-03-12 14:52:01 -08002312 int convertFeatureToNetworkType(String feature){
2313 int networkType = -1;
2314 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2315 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2316 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2317 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2318 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2319 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2320 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2321 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2322 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2323 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2324 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2325 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2326 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2327 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2328 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2329 }
2330 return networkType;
2331 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002332}