blob: 06be27bb651036b7a3bb785d31b8f9b0df68f04d [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
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500223 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700224
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
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500407 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700408
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
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500680 public boolean isSameUser(FeatureUser u) {
681 if (u == null) return false;
682
683 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
684 }
685
686 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
687 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
688 TextUtils.equals(mFeature, feature)) {
689 return true;
690 }
691 return false;
692 }
693
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800694 public String toString() {
695 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
696 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
697 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700698 }
699
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700700 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700701 public int startUsingNetworkFeature(int networkType, String feature,
702 IBinder binder) {
703 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800704 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700705 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800706 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700707 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700708 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700709 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800710 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700711
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700712 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700713
714 // TODO - move this into the MobileDataStateTracker
715 int usedNetworkType = networkType;
716 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savilleb7c92c72011-03-12 14:52:01 -0800717 usedNetworkType = convertFeatureToNetworkType(feature);
718 if (usedNetworkType < 0) {
719 Slog.e(TAG, "Can't match any netTracker!");
720 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700721 }
722 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700723
724 if (mProtectedNetworks.contains(usedNetworkType)) {
725 enforceConnectivityInternalPermission();
726 }
727
Robert Greenwalt2034b912009-08-12 16:08:25 -0700728 NetworkStateTracker network = mNetTrackers[usedNetworkType];
729 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800730 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700731 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700732 NetworkStateTracker radio = mNetTrackers[networkType];
733 NetworkInfo ni = network.getNetworkInfo();
734
735 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800736 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800737 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
738 return Phone.APN_TYPE_NOT_AVAILABLE;
739 } else {
740 // else make the attempt anyway - probably giving REQUEST_STARTED below
741 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700742 }
743
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500744 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
745
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700746 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500747 boolean addToList = true;
748 if (restoreTimer < 0) {
749 // In case there is no timer is specified for the feature,
750 // make sure we don't add duplicate entry with the same request.
751 for (FeatureUser u : mFeatureUsers) {
752 if (u.isSameUser(f)) {
753 // Duplicate user is found. Do not add.
754 addToList = false;
755 break;
756 }
757 }
758 }
759
760 if (addToList) mFeatureUsers.add(f);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700761 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
762 // this gets used for per-pid dns when connected
763 mNetRequestersPids[usedNetworkType].add(currentPid);
764 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700765 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700766
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700767 if (restoreTimer >= 0) {
768 mHandler.sendMessageDelayed(
769 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
770 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700771
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700772 if ((ni.isConnectedOrConnecting() == true) &&
773 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700774 if (ni.isConnected() == true) {
775 // add the pid-specific dns
Robert Greenwalt3afbead2010-07-23 15:46:26 -0700776 handleDnsConfigurationChange(networkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800777 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700778 return Phone.APN_ALREADY_ACTIVE;
779 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800780 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700781 return Phone.APN_REQUEST_STARTED;
782 }
783
784 // check if the radio in play can make another contact
785 // assume if cannot for now
786
Wink Savillee70c6f52010-12-03 12:01:38 -0800787 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700788 network.reconnect();
789 return Phone.APN_REQUEST_STARTED;
790 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800791 // need to remember this unsupported request so we respond appropriately on stop
792 synchronized(this) {
793 mFeatureUsers.add(f);
794 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
795 // this gets used for per-pid dns when connected
796 mNetRequestersPids[usedNetworkType].add(currentPid);
797 }
798 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700799 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700800 }
801 }
802 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800803 }
804
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700805 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800806 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700807 enforceChangePermission();
808
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700809 int pid = getCallingPid();
810 int uid = getCallingUid();
811
812 FeatureUser u = null;
813 boolean found = false;
814
815 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500816 for (FeatureUser x : mFeatureUsers) {
817 if (x.isSameUser(pid, uid, networkType, feature)) {
818 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700819 found = true;
820 break;
821 }
822 }
823 }
824 if (found && u != null) {
825 // stop regardless of how many other time this proc had called start
826 return stopUsingNetworkFeature(u, true);
827 } else {
828 // none found!
Wink Savillee70c6f52010-12-03 12:01:38 -0800829 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700830 return 1;
831 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700832 }
833
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700834 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
835 int networkType = u.mNetworkType;
836 String feature = u.mFeature;
837 int pid = u.mPid;
838 int uid = u.mUid;
839
840 NetworkStateTracker tracker = null;
841 boolean callTeardown = false; // used to carry our decision outside of sync block
842
Robert Greenwalt2034b912009-08-12 16:08:25 -0700843 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800844 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700845 ": " + feature);
846 }
Robert Greenwalt28f43012009-10-06 17:52:40 -0700847
The Android Open Source Project28527d22009-03-03 19:31:44 -0800848 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
849 return -1;
850 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700851
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700852 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
853 // sync block
854 synchronized(this) {
855 // check if this process still has an outstanding start request
856 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800857 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700858 return 1;
859 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700860 u.unlinkDeathRecipient();
861 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
862 // If we care about duplicate requests, check for that here.
863 //
864 // This is done to support the extension of a request - the app
865 // can request we start the network feature again and renew the
866 // auto-shutoff delay. Normal "stop" calls from the app though
867 // do not pay attention to duplicate requests - in effect the
868 // API does not refcount and a single stop will counter multiple starts.
869 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500870 for (FeatureUser x : mFeatureUsers) {
871 if (x.isSameUser(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800872 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700873 return 1;
874 }
875 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700876 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700877
878 // TODO - move to MobileDataStateTracker
879 int usedNetworkType = networkType;
880 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savilleb7c92c72011-03-12 14:52:01 -0800881 usedNetworkType = convertFeatureToNetworkType(feature);
882 if (usedNetworkType < 0) {
883 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700884 }
885 }
886 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700887 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800888 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700889 return -1;
890 }
891 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700892 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700893 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -0800894 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700895 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800896 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700897 "others still using it");
898 return 1;
899 }
900 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -0800901 } else {
902 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700903 }
904 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800905 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700906 if (callTeardown) {
907 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700908 return 1;
909 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -0700910 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700911 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800912 }
913
914 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700915 * @deprecated use requestRouteToHostAddress instead
916 *
The Android Open Source Project28527d22009-03-03 19:31:44 -0800917 * Ensure that a network route exists to deliver traffic to the specified
918 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700919 * @param networkType the type of the network over which traffic to the
920 * specified host is to be routed
921 * @param hostAddress the IP address of the host to which the route is
922 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -0800923 * @return {@code true} on success, {@code false} on failure
924 */
925 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700926 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
927
928 if (inetAddress == null) {
929 return false;
930 }
931
932 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
933 }
934
935 /**
936 * Ensure that a network route exists to deliver traffic to the specified
937 * host via the specified network interface.
938 * @param networkType the type of the network over which traffic to the
939 * specified host is to be routed
940 * @param hostAddress the IP address of the host to which the route is
941 * desired
942 * @return {@code true} on success, {@code false} on failure
943 */
944 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800945 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700946 if (mProtectedNetworks.contains(networkType)) {
947 enforceConnectivityInternalPermission();
948 }
949
The Android Open Source Project28527d22009-03-03 19:31:44 -0800950 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
951 return false;
952 }
953 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -0700954
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700955 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
956 tracker.isTeardownRequested()) {
Robert Greenwalt4666ed02009-09-10 15:06:20 -0700957 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800958 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700959 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -0700960 }
961 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800962 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700963 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700964 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700965 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwalt98107422011-07-22 11:55:33 -0700966 return addRouteToAddress(lp, addr);
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700967 } catch (UnknownHostException e) {}
968 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700969 }
970
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700971 private boolean addRoute(LinkProperties p, RouteInfo r) {
972 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltbd492212011-05-06 17:10:53 -0700973 }
974
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700975 private boolean removeRoute(LinkProperties p, RouteInfo r) {
976 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
977 }
978
Robert Greenwalt98107422011-07-22 11:55:33 -0700979 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
980 return modifyRouteToAddress(lp, addr, true);
981 }
982
983 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
984 return modifyRouteToAddress(lp, addr, false);
985 }
986
987 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd) {
988 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
989 if (bestRoute == null) {
990 bestRoute = RouteInfo.makeHostRoute(addr);
991 } else {
992 if (bestRoute.getGateway().equals(addr)) {
993 // if there is no better route, add the implied hostroute for our gateway
994 bestRoute = RouteInfo.makeHostRoute(addr);
995 } else {
996 // if we will connect to this through another route, add a direct route
997 // to it's gateway
998 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
999 }
1000 }
1001 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd);
1002 }
1003
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001004 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1005 boolean doAdd) {
1006 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1007
1008 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1009 loge("Error adding route - too much recursion");
1010 return false;
1011 }
1012
1013 if (r.isHostRoute() == false) {
1014 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1015 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001016 if (bestRoute.getGateway().equals(r.getGateway())) {
1017 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001018 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001019 } else {
1020 // if we will connect to our gateway through another route, add a direct
1021 // route to it's gateway
1022 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001023 }
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001024 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001025 }
1026 }
1027 if (doAdd) {
1028 if (DBG) log("Adding " + r + " for interface " + ifaceName);
1029 mAddedRoutes.add(r);
1030 try {
1031 mNetd.addRoute(ifaceName, r);
1032 } catch (Exception e) {
1033 // never crash - catch them all
1034 loge("Exception trying to add a route: " + e);
1035 return false;
1036 }
1037 } else {
1038 // if we remove this one and there are no more like it, then refcount==0 and
1039 // we can remove it from the table
1040 mAddedRoutes.remove(r);
1041 if (mAddedRoutes.contains(r) == false) {
1042 if (DBG) log("Removing " + r + " for interface " + ifaceName);
1043 try {
1044 mNetd.removeRoute(ifaceName, r);
1045 } catch (Exception e) {
1046 // never crash - catch them all
1047 loge("Exception trying to remove a route: " + e);
1048 return false;
1049 }
1050 } else {
1051 if (DBG) log("not removing " + r + " as it's still in use");
1052 }
1053 }
1054 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001055 }
1056
1057 /**
1058 * @see ConnectivityManager#getBackgroundDataSetting()
1059 */
1060 public boolean getBackgroundDataSetting() {
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001061 return mBackgroundDataEnabled.get();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001062 }
Robert Greenwalt0659da32009-07-16 17:21:39 -07001063
The Android Open Source Project28527d22009-03-03 19:31:44 -08001064 /**
1065 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1066 */
1067 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1068 mContext.enforceCallingOrSelfPermission(
1069 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1070 "ConnectivityService");
Robert Greenwalt0659da32009-07-16 17:21:39 -07001071
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001072 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1073
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001074 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1075 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1076 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001077
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001078 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwalt0ffdef12011-02-25 13:44:09 -08001079 Settings.Secure.putInt(mContext.getContentResolver(),
1080 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1081 Intent broadcast = new Intent(
1082 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1083 mContext.sendBroadcast(broadcast);
Robert Greenwalt0659da32009-07-16 17:21:39 -07001084 }
1085
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001086 /**
1087 * @see ConnectivityManager#getMobileDataEnabled()
1088 */
1089 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001090 // TODO: This detail should probably be in DataConnectionTracker's
1091 // which is where we store the value and maybe make this
1092 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001093 enforceAccessPermission();
1094 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1095 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savillee70c6f52010-12-03 12:01:38 -08001096 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001097 return retVal;
1098 }
1099
Robert Greenwalt34848c02011-03-25 13:09:25 -07001100 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001101 enforceConnectivityInternalPermission();
1102
Robert Greenwalt34848c02011-03-25 13:09:25 -07001103 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1104 (met ? ENABLED : DISABLED), networkType));
1105 }
1106
1107 private void handleSetDependencyMet(int networkType, boolean met) {
1108 if (mNetTrackers[networkType] != null) {
1109 if (DBG) {
1110 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1111 }
1112 mNetTrackers[networkType].setDependencyMet(met);
1113 }
1114 }
1115
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001116 /**
1117 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1118 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001119 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001120 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001121 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001122
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001123 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001124 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001125 }
1126
1127 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001128 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1129 if (DBG) {
1130 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001131 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001132 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001133 }
1134 }
1135
The Android Open Source Project28527d22009-03-03 19:31:44 -08001136 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001137 mContext.enforceCallingOrSelfPermission(
1138 android.Manifest.permission.ACCESS_NETWORK_STATE,
1139 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001140 }
1141
1142 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001143 mContext.enforceCallingOrSelfPermission(
1144 android.Manifest.permission.CHANGE_NETWORK_STATE,
1145 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001146 }
1147
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001148 // TODO Make this a special check when it goes public
1149 private void enforceTetherChangePermission() {
1150 mContext.enforceCallingOrSelfPermission(
1151 android.Manifest.permission.CHANGE_NETWORK_STATE,
1152 "ConnectivityService");
1153 }
1154
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001155 private void enforceTetherAccessPermission() {
1156 mContext.enforceCallingOrSelfPermission(
1157 android.Manifest.permission.ACCESS_NETWORK_STATE,
1158 "ConnectivityService");
1159 }
1160
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001161 private void enforceConnectivityInternalPermission() {
1162 mContext.enforceCallingOrSelfPermission(
1163 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1164 "ConnectivityService");
1165 }
1166
The Android Open Source Project28527d22009-03-03 19:31:44 -08001167 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001168 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1169 * network, we ignore it. If it is for the active network, we send out a
1170 * broadcast. But first, we check whether it might be possible to connect
1171 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001172 * @param info the {@code NetworkInfo} for the network
1173 */
1174 private void handleDisconnect(NetworkInfo info) {
1175
Robert Greenwalt2034b912009-08-12 16:08:25 -07001176 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001177
Robert Greenwalt2034b912009-08-12 16:08:25 -07001178 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001179 /*
1180 * If the disconnected network is not the active one, then don't report
1181 * this as a loss of connectivity. What probably happened is that we're
1182 * getting the disconnect for a network that we explicitly disabled
1183 * in accordance with network preference policies.
1184 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001185 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001186 List pids = mNetRequestersPids[prevNetType];
1187 for (int i = 0; i<pids.size(); i++) {
1188 Integer pid = (Integer)pids.get(i);
1189 // will remove them because the net's no longer connected
1190 // need to do this now as only now do we know the pids and
1191 // can properly null things that are no longer referenced.
1192 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001193 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001194 }
1195
The Android Open Source Project28527d22009-03-03 19:31:44 -08001196 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1197 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1198 if (info.isFailover()) {
1199 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1200 info.setFailover(false);
1201 }
1202 if (info.getReason() != null) {
1203 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1204 }
1205 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001206 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1207 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001208 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001209
Robert Greenwalt34848c02011-03-25 13:09:25 -07001210 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001211 tryFailover(prevNetType);
1212 if (mActiveDefaultNetwork != -1) {
1213 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001214 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1215 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001216 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001217 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1218 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001219 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001220 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001221
1222 // Reset interface if no other connections are using the same interface
1223 boolean doReset = true;
1224 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1225 if (linkProperties != null) {
1226 String oldIface = linkProperties.getInterfaceName();
1227 if (TextUtils.isEmpty(oldIface) == false) {
1228 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1229 if (networkStateTracker == null) continue;
1230 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1231 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1232 LinkProperties l = networkStateTracker.getLinkProperties();
1233 if (l == null) continue;
1234 if (oldIface.equals(l.getInterfaceName())) {
1235 doReset = false;
1236 break;
1237 }
1238 }
1239 }
1240 }
1241 }
1242
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001243 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001244 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001245
1246 sendStickyBroadcast(intent);
1247 /*
1248 * If the failover network is already connected, then immediately send
1249 * out a followup broadcast indicating successful failover
1250 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001251 if (mActiveDefaultNetwork != -1) {
1252 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001253 }
1254 }
1255
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001256 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001257 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001258 * If this is a default network, check if other defaults are available.
1259 * Try to reconnect on all available and let them hash it out when
1260 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001261 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001262 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001263 if (mActiveDefaultNetwork == prevNetType) {
1264 mActiveDefaultNetwork = -1;
1265 }
1266
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001267 // don't signal a reconnect for anything lower or equal priority than our
1268 // current connected default
1269 // TODO - don't filter by priority now - nice optimization but risky
1270// int currentPriority = -1;
1271// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001272// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001273// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001274 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001275 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001276 if (mNetConfigs[checkType] == null) continue;
1277 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001278
1279// Enabling the isAvailable() optimization caused mobile to not get
1280// selected if it was in the middle of error handling. Specifically
1281// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1282// would not be available and we wouldn't get connected to anything.
1283// So removing the isAvailable() optimization below for now. TODO: This
1284// optimization should work and we need to investigate why it doesn't work.
1285// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1286// complete before it is really complete.
1287// if (!mNetTrackers[checkType].isAvailable()) continue;
1288
Robert Greenwalt34848c02011-03-25 13:09:25 -07001289// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001290
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001291 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1292 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1293 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1294 checkInfo.setFailover(true);
1295 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001296 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001297 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001298 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001299 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001300 }
1301
1302 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001303 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1304 }
1305
1306 private void sendInetConditionBroadcast(NetworkInfo info) {
1307 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1308 }
1309
1310 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1311 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001312 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1313 if (info.isFailover()) {
1314 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1315 info.setFailover(false);
1316 }
1317 if (info.getReason() != null) {
1318 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1319 }
1320 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001321 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1322 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001323 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001324 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001325 sendStickyBroadcast(intent);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001326 }
1327
1328 /**
1329 * Called when an attempt to fail over to another network has failed.
1330 * @param info the {@link NetworkInfo} for the failed network
1331 */
1332 private void handleConnectionFailure(NetworkInfo info) {
1333 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001334
Robert Greenwalt2034b912009-08-12 16:08:25 -07001335 String reason = info.getReason();
1336 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001337
Robert Greenwalte981bc52010-10-08 16:35:52 -07001338 String reasonText;
1339 if (reason == null) {
1340 reasonText = ".";
1341 } else {
1342 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001343 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001344 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001345
1346 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1347 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1348 if (getActiveNetworkInfo() == null) {
1349 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1350 }
1351 if (reason != null) {
1352 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1353 }
1354 if (extraInfo != null) {
1355 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1356 }
1357 if (info.isFailover()) {
1358 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1359 info.setFailover(false);
1360 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001361
Robert Greenwalt34848c02011-03-25 13:09:25 -07001362 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001363 tryFailover(info.getType());
1364 if (mActiveDefaultNetwork != -1) {
1365 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001366 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1367 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001368 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001369 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1370 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001371 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001372
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001373 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001374 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001375 /*
1376 * If the failover network is already connected, then immediately send
1377 * out a followup broadcast indicating successful failover
1378 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001379 if (mActiveDefaultNetwork != -1) {
1380 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001381 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001382 }
1383
1384 private void sendStickyBroadcast(Intent intent) {
1385 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001386 if (!mSystemReady) {
1387 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001388 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001389 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1390 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001391 }
1392 }
1393
1394 void systemReady() {
Robert Greenwalt355205c2011-05-10 15:05:02 -07001395 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1396 mNetd = INetworkManagementService.Stub.asInterface(b);
1397
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001398 synchronized(this) {
1399 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001400 if (mInitialBroadcast != null) {
1401 mContext.sendStickyBroadcast(mInitialBroadcast);
1402 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001403 }
1404 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001405 // load the global proxy at startup
1406 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001407 }
1408
1409 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001410 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001411
1412 // snapshot isFailover, because sendConnectedBroadcast() resets it
1413 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001414 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001415
Robert Greenwalt2034b912009-08-12 16:08:25 -07001416 // if this is a default net and other default is running
1417 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001418 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001419 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1420 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001421 mNetConfigs[mActiveDefaultNetwork].priority >
1422 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001423 mNetworkPreference == mActiveDefaultNetwork) {
1424 // don't accept this one
Wink Savillee70c6f52010-12-03 12:01:38 -08001425 if (DBG) {
1426 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001427 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001428 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001429 teardown(thisNet);
1430 return;
1431 } else {
1432 // tear down the other
1433 NetworkStateTracker otherNet =
1434 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001435 if (DBG) {
1436 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001437 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001438 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001439 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001440 loge("Network declined teardown request");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001441 return;
1442 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001443 }
1444 }
1445 synchronized (ConnectivityService.this) {
1446 // have a new default network, release the transition wakelock in a second
1447 // if it's held. The second pause is to allow apps to reconnect over the
1448 // new network
1449 if (mNetTransitionWakeLock.isHeld()) {
1450 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001451 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001452 mNetTransitionWakeLockSerialNumber, 0),
1453 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001454 }
1455 }
1456 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001457 // this will cause us to come up initially as unconnected and switching
1458 // to connected after our normal pause unless somebody reports us as reall
1459 // disconnected
1460 mDefaultInetConditionPublished = 0;
1461 mDefaultConnectionSequence++;
1462 mInetConditionChangeInFlight = false;
1463 // Don't do this - if we never sign in stay, grey
1464 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001465 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001466 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001467 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001468 handleConnectivityChange(type, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001469 sendConnectedBroadcast(info);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001470 }
1471
The Android Open Source Project28527d22009-03-03 19:31:44 -08001472 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001473 * After a change in the connectivity state of a network. We're mainly
1474 * concerned with making sure that the list of DNS servers is set up
1475 * according to which networks are connected, and ensuring that the
1476 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001477 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001478 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07001479 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1480
The Android Open Source Project28527d22009-03-03 19:31:44 -08001481 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001482 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001483 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001484 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001485 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001486
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001487 LinkProperties curLp = mCurrentLinkProperties[netType];
1488 LinkProperties newLp = null;
1489
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001490 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001491 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07001492 if (VDBG) {
1493 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1494 " doReset=" + doReset + " resetMask=" + resetMask +
1495 "\n curLp=" + curLp +
1496 "\n newLp=" + newLp);
1497 }
1498
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001499 if (curLp != null) {
1500 if (curLp.isIdenticalInterfaceName(newLp)) {
1501 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1502 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1503 for (LinkAddress linkAddr : car.removed) {
1504 if (linkAddr.getAddress() instanceof Inet4Address) {
1505 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1506 }
1507 if (linkAddr.getAddress() instanceof Inet6Address) {
1508 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1509 }
Wink Saville051a6642011-07-13 13:44:13 -07001510 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001511 if (DBG) {
1512 log("handleConnectivityChange: addresses changed" +
1513 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1514 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07001515 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001516 } else {
1517 if (DBG) {
1518 log("handleConnectivityChange: address are the same reset per doReset" +
1519 " linkProperty[" + netType + "]:" +
1520 " resetMask=" + resetMask);
1521 }
Wink Saville051a6642011-07-13 13:44:13 -07001522 }
1523 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001524 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
1525 log("handleConnectivityChange: interface not not equivalent reset both" +
1526 " linkProperty[" + netType + "]:" +
1527 " resetMask=" + resetMask);
Wink Saville051a6642011-07-13 13:44:13 -07001528 }
Wink Saville051a6642011-07-13 13:44:13 -07001529 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07001530 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001531 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001532 }
1533 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001534 if (VDBG) {
1535 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1536 " doReset=" + doReset + " resetMask=" + resetMask +
1537 "\n curLp=" + curLp +
1538 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001539 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001540 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001541 mCurrentLinkProperties[netType] = newLp;
1542 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001543
Wink Saville051a6642011-07-13 13:44:13 -07001544 if (doReset || resetMask != 0) {
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001545 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1546 if (linkProperties != null) {
1547 String iface = linkProperties.getInterfaceName();
1548 if (TextUtils.isEmpty(iface) == false) {
Wink Saville051a6642011-07-13 13:44:13 -07001549 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1550 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001551 }
1552 }
1553 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001554
1555 // TODO: Temporary notifying upstread change to Tethering.
1556 // @see bug/4455071
1557 /** Notify TetheringService if interface name has been changed. */
1558 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1559 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1560 if (isTetheringSupported()) {
1561 mTethering.handleTetherIfaceChange();
1562 }
1563 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001564 }
1565
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001566 /**
1567 * Add and remove routes using the old properties (null if not previously connected),
1568 * new properties (null if becoming disconnected). May even be double null, which
1569 * is a noop.
1570 * Uses isLinkDefault to determine if default routes should be set or conversely if
1571 * host routes should be set to the dns servers
1572 */
1573 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1574 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07001575 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1576 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001577 if (curLp != null) {
1578 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07001579 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001580 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07001581 } else if (newLp != null) {
1582 routeDiff.added = newLp.getRoutes();
1583 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001584 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001585
Robert Greenwalt98107422011-07-22 11:55:33 -07001586 for (RouteInfo r : routeDiff.removed) {
1587 if (isLinkDefault || ! r.isDefaultRoute()) {
1588 removeRoute(curLp, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001589 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001590 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001591
Robert Greenwalt98107422011-07-22 11:55:33 -07001592 for (RouteInfo r : routeDiff.added) {
1593 if (isLinkDefault || ! r.isDefaultRoute()) {
1594 addRoute(newLp, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001595 }
1596 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001597
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001598 if (!isLinkDefault) {
1599 // handle DNS routes
Robert Greenwalt98107422011-07-22 11:55:33 -07001600 if (routeDiff.removed.size() == 0 && routeDiff.added.size() == 0) {
1601 // no change in routes, check for change in dns themselves
1602 for (InetAddress oldDns : dnsDiff.removed) {
1603 removeRouteToAddress(curLp, oldDns);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001604 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001605 for (InetAddress newDns : dnsDiff.added) {
1606 addRouteToAddress(newLp, newDns);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001607 }
Robert Greenwalt98107422011-07-22 11:55:33 -07001608 } else {
1609 // routes changed - remove all old dns entries and add new
1610 if (curLp != null) {
1611 for (InetAddress oldDns : curLp.getDnses()) {
1612 removeRouteToAddress(curLp, oldDns);
1613 }
1614 }
1615 if (newLp != null) {
1616 for (InetAddress newDns : newLp.getDnses()) {
1617 addRouteToAddress(newLp, newDns);
1618 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001619 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001620 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001621 }
1622 }
1623
1624
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001625 /**
1626 * Reads the network specific TCP buffer sizes from SystemProperties
1627 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1628 * wide use
1629 */
1630 public void updateNetworkSettings(NetworkStateTracker nt) {
1631 String key = nt.getTcpBufferSizesPropName();
1632 String bufferSizes = SystemProperties.get(key);
1633
1634 if (bufferSizes.length() == 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001635 loge(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001636
1637 // Setting to default values so we won't be stuck to previous values
1638 key = "net.tcp.buffersize.default";
1639 bufferSizes = SystemProperties.get(key);
1640 }
1641
1642 // Set values in kernel
1643 if (bufferSizes.length() != 0) {
1644 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001645 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001646 + "] which comes from [" + key + "]");
1647 }
1648 setBufferSize(bufferSizes);
1649 }
1650 }
1651
1652 /**
1653 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1654 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1655 *
1656 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1657 * writeMin, writeInitial, writeMax"
1658 */
1659 private void setBufferSize(String bufferSizes) {
1660 try {
1661 String[] values = bufferSizes.split(",");
1662
1663 if (values.length == 6) {
1664 final String prefix = "/sys/kernel/ipv4/tcp_";
1665 stringToFile(prefix + "rmem_min", values[0]);
1666 stringToFile(prefix + "rmem_def", values[1]);
1667 stringToFile(prefix + "rmem_max", values[2]);
1668 stringToFile(prefix + "wmem_min", values[3]);
1669 stringToFile(prefix + "wmem_def", values[4]);
1670 stringToFile(prefix + "wmem_max", values[5]);
1671 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001672 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001673 }
1674 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001675 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001676 }
1677 }
1678
1679 /**
1680 * Writes string to file. Basically same as "echo -n $string > $filename"
1681 *
1682 * @param filename
1683 * @param string
1684 * @throws IOException
1685 */
1686 private void stringToFile(String filename, String string) throws IOException {
1687 FileWriter out = new FileWriter(filename);
1688 try {
1689 out.write(string);
1690 } finally {
1691 out.close();
1692 }
1693 }
1694
1695
Robert Greenwalt2034b912009-08-12 16:08:25 -07001696 /**
1697 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1698 * on the highest priority active net which this process requested.
1699 * If there aren't any, clear it out
1700 */
1701 private void reassessPidDns(int myPid, boolean doBump)
1702 {
Wink Savillee70c6f52010-12-03 12:01:38 -08001703 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001704 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001705 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001706 continue;
1707 }
1708 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001709 if (nt.getNetworkInfo().isConnected() &&
1710 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001711 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001712 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001713 List pids = mNetRequestersPids[i];
1714 for (int j=0; j<pids.size(); j++) {
1715 Integer pid = (Integer)pids.get(j);
1716 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001717 Collection<InetAddress> dnses = p.getDnses();
1718 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001719 if (doBump) {
1720 bumpDns();
1721 }
1722 return;
1723 }
1724 }
1725 }
1726 }
1727 // nothing found - delete
1728 for (int i = 1; ; i++) {
1729 String prop = "net.dns" + i + "." + myPid;
1730 if (SystemProperties.get(prop).length() == 0) {
1731 if (doBump) {
1732 bumpDns();
1733 }
1734 return;
1735 }
1736 SystemProperties.set(prop, "");
1737 }
1738 }
1739
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001740 // return true if results in a change
1741 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001742 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001743 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001744 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001745 String dnsString = dns.getHostAddress();
1746 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1747 changed = true;
1748 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1749 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001750 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001751 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001752 }
1753
1754 private void bumpDns() {
1755 /*
1756 * Bump the property that tells the name resolver library to reread
1757 * the DNS server list from the properties.
1758 */
1759 String propVal = SystemProperties.get("net.dnschange");
1760 int n = 0;
1761 if (propVal.length() != 0) {
1762 try {
1763 n = Integer.parseInt(propVal);
1764 } catch (NumberFormatException e) {}
1765 }
1766 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001767 /*
1768 * Tell the VMs to toss their DNS caches
1769 */
1770 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1771 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08001772 /*
1773 * Connectivity events can happen before boot has completed ...
1774 */
1775 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07001776 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001777 }
1778
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001779 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001780 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001781 NetworkStateTracker nt = mNetTrackers[netType];
1782 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001783 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001784 if (p == null) return;
1785 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001786 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001787 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001788 int j = 1;
Robert Greenwalt94daa182010-09-01 11:34:05 -07001789 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001790 String dnsString = mDefaultDns.getHostAddress();
1791 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1792 if (DBG) {
1793 log("no dns provided - using " + dnsString);
1794 }
1795 changed = true;
1796 SystemProperties.set("net.dns1", dnsString);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001797 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001798 j++;
1799 } else {
1800 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001801 String dnsString = dns.getHostAddress();
1802 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1803 j++;
1804 continue;
1805 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001806 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001807 log("adding dns " + dns + " for " +
Robert Greenwalt94daa182010-09-01 11:34:05 -07001808 nt.getNetworkInfo().getTypeName());
1809 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001810 changed = true;
1811 SystemProperties.set("net.dns" + j++, dnsString);
Robert Greenwalt94daa182010-09-01 11:34:05 -07001812 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001813 }
1814 for (int k=j ; k<mNumDnsEntries; k++) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001815 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1816 if (DBG) log("erasing net.dns" + k);
1817 changed = true;
1818 SystemProperties.set("net.dns" + k, "");
1819 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001820 }
1821 mNumDnsEntries = j;
1822 } else {
1823 // set per-pid dns for attached secondary nets
1824 List pids = mNetRequestersPids[netType];
1825 for (int y=0; y< pids.size(); y++) {
1826 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001827 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001828 }
1829 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001830 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001831 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001832 }
1833
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001834 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001835 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1836 NETWORK_RESTORE_DELAY_PROP_NAME);
1837 if(restoreDefaultNetworkDelayStr != null &&
1838 restoreDefaultNetworkDelayStr.length() != 0) {
1839 try {
1840 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1841 } catch (NumberFormatException e) {
1842 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001843 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001844 // if the system property isn't set, use the value for the apn type
1845 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1846
1847 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1848 (mNetConfigs[networkType] != null)) {
1849 ret = mNetConfigs[networkType].restoreTime;
1850 }
1851 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001852 }
1853
1854 @Override
1855 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001856 if (mContext.checkCallingOrSelfPermission(
1857 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001858 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001859 pw.println("Permission Denial: can't dump ConnectivityService " +
1860 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1861 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001862 return;
1863 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001864 pw.println();
1865 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001866 if (nst != null) {
1867 if (nst.getNetworkInfo().isConnected()) {
1868 pw.println("Active network: " + nst.getNetworkInfo().
1869 getTypeName());
1870 }
1871 pw.println(nst.getNetworkInfo());
1872 pw.println(nst);
1873 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001874 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001875 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001876
1877 pw.println("Network Requester Pids:");
1878 for (int net : mPriorityList) {
1879 String pidString = net + ": ";
1880 for (Object pid : mNetRequestersPids[net]) {
1881 pidString = pidString + pid.toString() + ", ";
1882 }
1883 pw.println(pidString);
1884 }
1885 pw.println();
1886
1887 pw.println("FeatureUsers:");
1888 for (Object requester : mFeatureUsers) {
1889 pw.println(requester.toString());
1890 }
1891 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001892
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001893 synchronized (this) {
1894 pw.println("NetworkTranstionWakeLock is currently " +
1895 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1896 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1897 }
1898 pw.println();
1899
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001900 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07001901
1902 if (mInetLog != null) {
1903 pw.println();
1904 pw.println("Inet condition reports:");
1905 for(int i = 0; i < mInetLog.size(); i++) {
1906 pw.println(mInetLog.get(i));
1907 }
1908 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001909 }
1910
Robert Greenwalt2034b912009-08-12 16:08:25 -07001911 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001912 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07001913 public MyHandler(Looper looper) {
1914 super(looper);
1915 }
1916
The Android Open Source Project28527d22009-03-03 19:31:44 -08001917 @Override
1918 public void handleMessage(Message msg) {
1919 NetworkInfo info;
1920 switch (msg.what) {
1921 case NetworkStateTracker.EVENT_STATE_CHANGED:
1922 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08001923 int type = info.getType();
1924 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08001925
Wink Savillee70c6f52010-12-03 12:01:38 -08001926 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07001927 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08001928 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001929
1930 // Connectivity state changed:
1931 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07001932 // [12-9] Network subtype (for mobile network, as defined
1933 // by TelephonyManager)
1934 // [8-3] Detailed state ordinal (as defined by
1935 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001936 // [2-0] Network type (as defined by ConnectivityManager)
1937 int eventLogParam = (info.getType() & 0x7) |
1938 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1939 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08001940 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07001941 eventLogParam);
1942
1943 if (info.getDetailedState() ==
1944 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001945 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001946 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001947 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001948 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001949 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001950 // the logic here is, handle SUSPENDED the same as
1951 // DISCONNECTED. The only difference being we are
1952 // broadcasting an intent with NetworkInfo that's
1953 // suspended. This allows the applications an
1954 // opportunity to handle DISCONNECTED and SUSPENDED
1955 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001956 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001957 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001958 handleConnect(info);
1959 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001960 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001961 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001962 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05001963 // TODO: Temporary allowing network configuration
1964 // change not resetting sockets.
1965 // @see bug/4455071
1966 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001967 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001968 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001969 String causedBy = null;
1970 synchronized (ConnectivityService.this) {
1971 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
1972 mNetTransitionWakeLock.isHeld()) {
1973 mNetTransitionWakeLock.release();
1974 causedBy = mNetTransitionWakeLockCausedBy;
1975 }
1976 }
1977 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001978 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001979 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07001980 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001981 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001982 FeatureUser u = (FeatureUser)msg.obj;
1983 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07001984 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001985 case EVENT_INET_CONDITION_CHANGE:
1986 {
1987 int netType = msg.arg1;
1988 int condition = msg.arg2;
1989 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001990 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001991 }
1992 case EVENT_INET_CONDITION_HOLD_END:
1993 {
1994 int netType = msg.arg1;
1995 int sequence = msg.arg2;
1996 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07001997 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001998 }
1999 case EVENT_SET_NETWORK_PREFERENCE:
2000 {
2001 int preference = msg.arg1;
2002 handleSetNetworkPreference(preference);
2003 break;
2004 }
2005 case EVENT_SET_BACKGROUND_DATA:
2006 {
2007 boolean enabled = (msg.arg1 == ENABLED);
2008 handleSetBackgroundData(enabled);
2009 break;
2010 }
2011 case EVENT_SET_MOBILE_DATA:
2012 {
2013 boolean enabled = (msg.arg1 == ENABLED);
2014 handleSetMobileData(enabled);
2015 break;
2016 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002017 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2018 {
2019 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002020 break;
2021 }
2022 case EVENT_SET_DEPENDENCY_MET:
2023 {
2024 boolean met = (msg.arg1 == ENABLED);
2025 handleSetDependencyMet(msg.arg2, met);
2026 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002027 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002028 }
2029 }
2030 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002031
2032 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002033 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002034 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002035
2036 if (isTetheringSupported()) {
2037 return mTethering.tether(iface);
2038 } else {
2039 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2040 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002041 }
2042
2043 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002044 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002045 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002046
2047 if (isTetheringSupported()) {
2048 return mTethering.untether(iface);
2049 } else {
2050 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2051 }
2052 }
2053
2054 // javadoc from interface
2055 public int getLastTetherError(String iface) {
2056 enforceTetherAccessPermission();
2057
2058 if (isTetheringSupported()) {
2059 return mTethering.getLastTetherError(iface);
2060 } else {
2061 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2062 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002063 }
2064
2065 // TODO - proper iface API for selection by property, inspection, etc
2066 public String[] getTetherableUsbRegexs() {
2067 enforceTetherAccessPermission();
2068 if (isTetheringSupported()) {
2069 return mTethering.getTetherableUsbRegexs();
2070 } else {
2071 return new String[0];
2072 }
2073 }
2074
2075 public String[] getTetherableWifiRegexs() {
2076 enforceTetherAccessPermission();
2077 if (isTetheringSupported()) {
2078 return mTethering.getTetherableWifiRegexs();
2079 } else {
2080 return new String[0];
2081 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002082 }
2083
Danica Chang96567052010-08-11 14:54:43 -07002084 public String[] getTetherableBluetoothRegexs() {
2085 enforceTetherAccessPermission();
2086 if (isTetheringSupported()) {
2087 return mTethering.getTetherableBluetoothRegexs();
2088 } else {
2089 return new String[0];
2090 }
2091 }
2092
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002093 // TODO - move iface listing, queries, etc to new module
2094 // javadoc from interface
2095 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002096 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002097 return mTethering.getTetherableIfaces();
2098 }
2099
2100 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002101 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002102 return mTethering.getTetheredIfaces();
2103 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002104
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002105 public String[] getTetheringErroredIfaces() {
2106 enforceTetherAccessPermission();
2107 return mTethering.getErroredIfaces();
2108 }
2109
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002110 // if ro.tether.denied = true we default to no tethering
2111 // gservices could set the secure setting to 1 though to enable it on a build where it
2112 // had previously been turned off.
2113 public boolean isTetheringSupported() {
2114 enforceTetherAccessPermission();
2115 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002116 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2117 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2118 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002119 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002120
2121 // An API NetworkStateTrackers can call when they lose their network.
2122 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2123 // whichever happens first. The timer is started by the first caller and not
2124 // restarted by subsequent callers.
2125 public void requestNetworkTransitionWakelock(String forWhom) {
2126 enforceConnectivityInternalPermission();
2127 synchronized (this) {
2128 if (mNetTransitionWakeLock.isHeld()) return;
2129 mNetTransitionWakeLockSerialNumber++;
2130 mNetTransitionWakeLock.acquire();
2131 mNetTransitionWakeLockCausedBy = forWhom;
2132 }
2133 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002134 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002135 mNetTransitionWakeLockSerialNumber, 0),
2136 mNetTransitionWakeLockTimeout);
2137 return;
2138 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002139
Robert Greenwalt986c7412010-09-08 15:24:47 -07002140 // 100 percent is full good, 0 is full bad.
2141 public void reportInetCondition(int networkType, int percentage) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002142 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002143 mContext.enforceCallingOrSelfPermission(
2144 android.Manifest.permission.STATUS_BAR,
2145 "ConnectivityService");
2146
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002147 if (DBG) {
2148 int pid = getCallingPid();
2149 int uid = getCallingUid();
2150 String s = pid + "(" + uid + ") reports inet is " +
2151 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2152 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2153 mInetLog.add(s);
2154 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2155 mInetLog.remove(0);
2156 }
2157 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002158 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002159 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2160 }
2161
2162 private void handleInetConditionChange(int netType, int condition) {
2163 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002164 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002165 netType + ", condition=" + condition +
2166 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2167 }
2168 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002169 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002170 return;
2171 }
2172 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002173 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002174 return;
2175 }
2176 mDefaultInetCondition = condition;
2177 int delay;
2178 if (mInetConditionChangeInFlight == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002179 if (DBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002180 // setup a new hold to debounce this
2181 if (mDefaultInetCondition > 50) {
2182 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2183 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2184 } else {
2185 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2186 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2187 }
2188 mInetConditionChangeInFlight = true;
2189 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2190 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2191 } else {
2192 // we've set the new condition, when this hold ends that will get
2193 // picked up
Wink Savillee70c6f52010-12-03 12:01:38 -08002194 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002195 }
2196 }
2197
2198 private void handleInetConditionHoldEnd(int netType, int sequence) {
2199 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002200 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002201 ", condition =" + mDefaultInetCondition +
2202 ", published condition =" + mDefaultInetConditionPublished);
2203 }
2204 mInetConditionChangeInFlight = false;
2205
2206 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002207 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002208 return;
2209 }
2210 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002211 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002212 return;
2213 }
2214 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002215 if (DBG) log("no change in condition - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002216 return;
2217 }
2218 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2219 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002220 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002221 return;
2222 }
2223 mDefaultInetConditionPublished = mDefaultInetCondition;
2224 sendInetConditionBroadcast(networkInfo);
2225 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002226 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002227
2228 public synchronized ProxyProperties getProxy() {
2229 if (mGlobalProxy != null) return mGlobalProxy;
2230 if (mDefaultProxy != null) return mDefaultProxy;
2231 return null;
2232 }
2233
2234 public void setGlobalProxy(ProxyProperties proxyProperties) {
2235 enforceChangePermission();
2236 synchronized (mGlobalProxyLock) {
2237 if (proxyProperties == mGlobalProxy) return;
2238 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2239 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2240
2241 String host = "";
2242 int port = 0;
2243 String exclList = "";
2244 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2245 mGlobalProxy = new ProxyProperties(proxyProperties);
2246 host = mGlobalProxy.getHost();
2247 port = mGlobalProxy.getPort();
2248 exclList = mGlobalProxy.getExclusionList();
2249 } else {
2250 mGlobalProxy = null;
2251 }
2252 ContentResolver res = mContext.getContentResolver();
2253 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2254 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002255 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002256 exclList);
2257 }
2258
2259 if (mGlobalProxy == null) {
2260 proxyProperties = mDefaultProxy;
2261 }
2262 sendProxyBroadcast(proxyProperties);
2263 }
2264
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002265 private void loadGlobalProxy() {
2266 ContentResolver res = mContext.getContentResolver();
2267 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2268 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2269 String exclList = Settings.Secure.getString(res,
2270 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2271 if (!TextUtils.isEmpty(host)) {
2272 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2273 synchronized (mGlobalProxyLock) {
2274 mGlobalProxy = proxyProperties;
2275 }
2276 }
2277 }
2278
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002279 public ProxyProperties getGlobalProxy() {
2280 synchronized (mGlobalProxyLock) {
2281 return mGlobalProxy;
2282 }
2283 }
2284
2285 private void handleApplyDefaultProxy(int type) {
2286 // check if new default - push it out to all VM if so
2287 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2288 synchronized (this) {
2289 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2290 if (mDefaultProxy == proxy) return;
2291 if (!TextUtils.isEmpty(proxy.getHost())) {
2292 mDefaultProxy = proxy;
2293 } else {
2294 mDefaultProxy = null;
2295 }
2296 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002297 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002298 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2299 if (mGlobalProxy != null) return;
2300 sendProxyBroadcast(proxy);
2301 }
2302
2303 private void handleDeprecatedGlobalHttpProxy() {
2304 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2305 Settings.Secure.HTTP_PROXY);
2306 if (!TextUtils.isEmpty(proxy)) {
2307 String data[] = proxy.split(":");
2308 String proxyHost = data[0];
2309 int proxyPort = 8080;
2310 if (data.length > 1) {
2311 try {
2312 proxyPort = Integer.parseInt(data[1]);
2313 } catch (NumberFormatException e) {
2314 return;
2315 }
2316 }
2317 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2318 setGlobalProxy(p);
2319 }
2320 }
2321
2322 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002323 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savillee70c6f52010-12-03 12:01:38 -08002324 log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002325 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002326 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2327 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002328 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002329 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002330 }
2331
2332 private static class SettingsObserver extends ContentObserver {
2333 private int mWhat;
2334 private Handler mHandler;
2335 SettingsObserver(Handler handler, int what) {
2336 super(handler);
2337 mHandler = handler;
2338 mWhat = what;
2339 }
2340
2341 void observe(Context context) {
2342 ContentResolver resolver = context.getContentResolver();
2343 resolver.registerContentObserver(Settings.Secure.getUriFor(
2344 Settings.Secure.HTTP_PROXY), false, this);
2345 }
2346
2347 @Override
2348 public void onChange(boolean selfChange) {
2349 mHandler.obtainMessage(mWhat).sendToTarget();
2350 }
2351 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002352
2353 private void log(String s) {
2354 Slog.d(TAG, s);
2355 }
2356
2357 private void loge(String s) {
2358 Slog.e(TAG, s);
2359 }
Wink Savilleb7c92c72011-03-12 14:52:01 -08002360 int convertFeatureToNetworkType(String feature){
2361 int networkType = -1;
2362 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2363 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2364 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2365 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2366 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2367 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2368 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2369 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2370 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2371 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2372 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2373 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2374 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2375 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2376 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2377 }
2378 return networkType;
2379 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002380}