blob: c9ab806dfb242080ec7da0a58e259eba5ffd2d8a [file] [log] [blame]
The Android Open Source Project9066cfe2009-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 Ganesh15c74392010-12-21 22:31:44 -080019import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.ContentResolver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.pm.PackageManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070024import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080026import android.net.DummyDataStateTracker;
Benoit Goby08c39c62010-12-22 14:29:40 -080027import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.net.IConnectivityManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070029import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080030import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070031import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070033import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.net.NetworkInfo;
35import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070036import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070037import android.net.Proxy;
38import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070039import android.net.RouteInfo;
Hung-ying Tyan6b818de2011-01-19 16:48:38 +080040import android.net.vpn.VpnManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.net.wifi.WifiStateTracker;
42import android.os.Binder;
43import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070044import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070045import android.os.IBinder;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070046import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.Looper;
48import android.os.Message;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070049import android.os.PowerManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070050import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.ServiceManager;
52import android.os.SystemProperties;
53import android.provider.Settings;
Robert Greenwalt42acef32009-08-12 16:08:25 -070054import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080056import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057
Robert Greenwalt42acef32009-08-12 16:08:25 -070058import com.android.internal.telephony.Phone;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080059import com.android.server.connectivity.Tethering;
60
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -070062import java.io.FileWriter;
63import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.io.PrintWriter;
Wink Savillee8222252011-07-13 13:44:13 -070065import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070066import java.net.InetAddress;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070067import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070068import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -070069import java.util.ArrayList;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070070import java.util.Collection;
Robert Greenwaltd825ea42010-12-29 16:15:02 -080071import java.util.concurrent.atomic.AtomicBoolean;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -070072import java.util.GregorianCalendar;
Robert Greenwalt42acef32009-08-12 16:08:25 -070073import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074
75/**
76 * @hide
77 */
78public class ConnectivityService extends IConnectivityManager.Stub {
79
Robert Greenwaltba175a52010-10-05 19:12:26 -070080 private static final boolean DBG = true;
Wink Savillee8222252011-07-13 13:44:13 -070081 private static final boolean VDBG = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 private static final String TAG = "ConnectivityService";
83
Robert Greenwalt42acef32009-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 Greenwaltf43396c2011-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 Greenwaltd0e18ff2010-01-26 11:40:34 -080094 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -080095 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080096
The Android Open Source Project9066cfe2009-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 Greenwalt42acef32009-08-12 16:08:25 -0700103
104 /**
Wink Savillee8222252011-07-13 13:44:13 -0700105 * The link properties that define the current links
106 */
107 private LinkProperties mCurrentLinkProperties[];
108
109 /**
Robert Greenwalt42acef32009-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 Sheriffa2a1b912010-06-07 09:03:04 -0700115 private WifiWatchdogService mWifiWatchdogService;
116
Robert Greenwalt42acef32009-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 Project9066cfe2009-03-03 19:31:44 -0800122 private Context mContext;
123 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700124 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-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 Project9066cfe2009-03-03 19:31:44 -0800130
131 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132
133 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700134 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
Robert Greenwaltd825ea42010-12-29 16:15:02 -0800136 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
137
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700138 private INetworkManagementService mNetd;
139
Robert Greenwalt8dcc28b2010-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 Greenwaltf3331232010-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 Greenwalt434203a2010-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 Greenwaltd55a6b42011-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 Greenwalt42acef32009-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 Ondo3bed4c92011-07-19 11:23:37 -0500223 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700224
Mike Lockwood0f79b542009-08-14 14:18:49 -0400225 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800226 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400227
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700228 private PowerManager.WakeLock mNetTransitionWakeLock;
229 private String mNetTransitionWakeLockCausedBy = "";
230 private int mNetTransitionWakeLockSerialNumber;
231 private int mNetTransitionWakeLockTimeout;
232
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700233 private InetAddress mDefaultDns;
234
Robert Greenwalt0a46db52011-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 Greenwalt4e8dfef2010-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 Greenwalt434203a2010-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 Greenwaltd55a6b42011-03-25 13:09:25 -0700251 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700252 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700253
Robert Greenwalt511288a2009-12-07 11:33:18 -0800254 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700255 public int mSimultaneity;
256 public int mType;
257 public RadioAttributes(String init) {
258 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700259 mType = Integer.parseInt(fragments[0]);
260 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700261 }
262 }
263 RadioAttributes[] mRadioAttributes;
264
Robert Greenwalt50393202011-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 Savillebb08caf2010-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 Project9066cfe2009-03-03 19:31:44 -0800271 }
Wink Savillebb08caf2010-09-02 19:23:52 -0700272 return sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 private ConnectivityService(Context context) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800276 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800277
Wink Savillebb08caf2010-09-02 19:23:52 -0700278 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
279 handlerThread.start();
280 mHandler = new MyHandler(handlerThread.getLooper());
281
Robert Greenwaltd825ea42010-12-29 16:15:02 -0800282 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
283 Settings.Secure.BACKGROUND_DATA, 1) == 1);
284
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800285 // setup our unique device name
Robert Greenwalt733c6292010-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 Greenwaltde8383c2010-01-14 17:47:58 -0800293 }
294
Robert Greenwalte90aa5e2010-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 Greenwalte5903732011-02-22 16:00:42 -0800303 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
304 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800305 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700306 }
307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 mContext = context;
Robert Greenwalt14f2ef42010-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 Greenwalt42acef32009-08-12 16:08:25 -0700315 mNetTrackers = new NetworkStateTracker[
316 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700317 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700320
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700321 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700322 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700323
Robert Greenwalt42acef32009-08-12 16:08:25 -0700324 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700325 String[] raStrings = context.getResources().getStringArray(
326 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-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 Savilleed9c02b2010-12-03 12:01:38 -0800330 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700331 continue;
332 }
333 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800334 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700335 r.mType);
336 continue;
337 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700338 mRadioAttributes[r.mType] = r;
339 }
340
Robert Greenwalt5154ae762009-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 Greenwaltd55a6b42011-03-25 13:09:25 -0700345 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700346 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800347 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700348 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700349 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700350 }
Wink Saville975c8482011-04-07 14:23:45 -0700351 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800352 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700353 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700354 continue;
355 }
Wink Saville975c8482011-04-07 14:23:45 -0700356 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800357 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700358 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700359 continue;
360 }
Wink Saville975c8482011-04-07 14:23:45 -0700361 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700362 mNetworksDefined++;
363 } catch(Exception e) {
364 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700365 }
366 }
367
Robert Greenwalt50393202011-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 Greenwalt5154ae762009-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 Greenwaltd55a6b42011-03-25 13:09:25 -0700386 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700387 if (na == null) continue;
Wink Saville975c8482011-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 Greenwalt5154ae762009-10-30 14:17:42 -0700392 }
393 continue;
394 }
Wink Saville975c8482011-04-07 14:23:45 -0700395 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-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 Greenwalt42acef32009-08-12 16:08:25 -0700404 mNetRequestersPids[i] = new ArrayList();
405 }
406
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500407 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700408
Robert Greenwalt5154ae762009-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 Project9066cfe2009-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 Greenwalt5154ae762009-10-30 14:17:42 -0700420 for (int netType : mPriorityList) {
Wink Saville975c8482011-04-07 14:23:45 -0700421 switch (mNetConfigs[netType].radio) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700422 case ConnectivityManager.TYPE_WIFI:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800423 if (DBG) log("Starting Wifi Service.");
Wink Savillec7a98342010-08-13 16:11:42 -0700424 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700425 WifiService wifiService = new WifiService(context);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700426 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700427 wifiService.checkAndStartWifi();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700428 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Savillec7a98342010-08-13 16:11:42 -0700429 wst.startMonitoring(context, mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700431 //TODO: as part of WWS refactor, create only when needed
Irfan Sheriff0d255342010-07-28 09:35:20 -0700432 mWifiWatchdogService = new WifiWatchdogService(context);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700433
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700434 break;
435 case ConnectivityManager.TYPE_MOBILE:
Wink Savillec7a98342010-08-13 16:11:42 -0700436 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700437 mNetConfigs[netType].name);
Wink Savillec7a98342010-08-13 16:11:42 -0700438 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700439 break;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800440 case ConnectivityManager.TYPE_DUMMY:
441 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700442 mNetConfigs[netType].name);
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800443 mNetTrackers[netType].startMonitoring(context, mHandler);
444 break;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800445 case ConnectivityManager.TYPE_BLUETOOTH:
446 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
447 mNetTrackers[netType].startMonitoring(context, mHandler);
448 break;
Benoit Goby08c39c62010-12-22 14:29:40 -0800449 case ConnectivityManager.TYPE_ETHERNET:
450 mNetTrackers[netType] = EthernetDataTracker.getInstance();
451 mNetTrackers[netType].startMonitoring(context, mHandler);
452 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700453 default:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800454 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Saville975c8482011-04-07 14:23:45 -0700455 mNetConfigs[netType].radio);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700456 continue;
457 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700458 mCurrentLinkProperties[netType] = null;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700459 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800460
Robert Greenwaltdfadaea2010-03-11 15:03:08 -0800461 mTethering = new Tethering(mContext, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700462 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700463 mTethering.getTetherableWifiRegexs().length != 0 ||
464 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700465 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800466
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700467 if (DBG) {
468 mInetLog = new ArrayList();
469 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700470
471 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
472 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800473
474 loadGlobalProxy();
Hung-ying Tyan6b818de2011-01-19 16:48:38 +0800475
476 VpnManager.startVpnService(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 }
478
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700481 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 * @param preference the new preference
483 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700484 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700486
487 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 }
489
490 public int getNetworkPreference() {
491 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700492 int preference;
493 synchronized(this) {
494 preference = mNetworkPreference;
495 }
496 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 }
498
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700499 private void handleSetNetworkPreference(int preference) {
500 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700501 mNetConfigs[preference] != null &&
502 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-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 Project9066cfe2009-03-03 19:31:44 -0800512 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700513
The Android Open Source Project9066cfe2009-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 Greenwalt86e9e552009-07-16 17:21:39 -0700525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700527 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-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 Greenwalt42acef32009-08-12 16:08:25 -0700534 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 return;
536
Robert Greenwalt42acef32009-08-12 16:08:25 -0700537 if (!mNetTrackers[mNetworkPreference].isAvailable())
538 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539
Robert Greenwalt42acef32009-08-12 16:08:25 -0700540 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700541 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700542 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700543 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800544 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700545 " in enforcePreference");
546 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700547 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-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 Greenwalt86e9e552009-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 Project9066cfe2009-03-03 19:31:44 -0800567 */
568 public NetworkInfo getActiveNetworkInfo() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700569 return getNetworkInfo(mActiveDefaultNetwork);
The Android Open Source Project9066cfe2009-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 Greenwalt5154ae762009-10-30 14:17:42 -0700584 NetworkInfo[] result = new NetworkInfo[mNetworksDefined];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 int i = 0;
586 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700587 if(t != null) result[i++] = t.getNetworkInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 }
589 return result;
590 }
591
Robert Greenwaltd192dad2010-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 Greenwalt59911582011-05-20 12:23:41 -0700601 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-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 Project9066cfe2009-03-03 19:31:44 -0800613 public boolean setRadios(boolean turnOn) {
614 boolean result = true;
615 enforceChangePermission();
616 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700617 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-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 Greenwalt9c75d4a2009-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 Greenwalt42acef32009-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 Greenwaltb9285352009-12-21 18:24:07 -0800644 long mCreateTime;
Robert Greenwalt42acef32009-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 Greenwaltb9285352009-12-21 18:24:07 -0800653 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700654
Robert Greenwalt42acef32009-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 Savilleed9c02b2010-12-03 12:01:38 -0800667 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800668 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
669 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700670 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700671 }
672
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700673 public void expire() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800674 log("ConnectivityService FeatureUser expire(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800675 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
676 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700677 stopUsingNetworkFeature(this, false);
678 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800679
Kazuhiro Ondo3bed4c92011-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 Greenwaltb9285352009-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 Greenwalt42acef32009-08-12 16:08:25 -0700698 }
699
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700700 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700701 public int startUsingNetworkFeature(int networkType, String feature,
702 IBinder binder) {
703 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800704 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700707 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700708 mNetConfigs[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700709 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700711
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700712 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700713
714 // TODO - move this into the MobileDataStateTracker
715 int usedNetworkType = networkType;
716 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville9d7d6282011-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 Greenwalt42acef32009-08-12 16:08:25 -0700721 }
722 }
Robert Greenwalt50393202011-06-21 17:26:14 -0700723
724 if (mProtectedNetworks.contains(usedNetworkType)) {
725 enforceConnectivityInternalPermission();
726 }
727
Robert Greenwalt42acef32009-08-12 16:08:25 -0700728 NetworkStateTracker network = mNetTrackers[usedNetworkType];
729 if (network != null) {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800730 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt42acef32009-08-12 16:08:25 -0700731 if (usedNetworkType != networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700732 NetworkStateTracker radio = mNetTrackers[networkType];
733 NetworkInfo ni = network.getNetworkInfo();
734
735 if (ni.isAvailable() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800736 if (DBG) log("special network not available");
Robert Greenwalte32e8122010-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 Greenwalt42acef32009-08-12 16:08:25 -0700742 }
743
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500744 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
745
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700746 synchronized(this) {
Kazuhiro Ondo3bed4c92011-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 Greenwalt9c75d4a2009-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 Greenwalt42acef32009-08-12 16:08:25 -0700765 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700766
Robert Greenwaltf2102f72011-05-03 19:02:44 -0700767 if (restoreTimer >= 0) {
768 mHandler.sendMessageDelayed(
769 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
770 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700771
Robert Greenwalta64bf832009-08-19 20:19:33 -0700772 if ((ni.isConnectedOrConnecting() == true) &&
773 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700774 if (ni.isConnected() == true) {
775 // add the pid-specific dns
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -0700776 handleDnsConfigurationChange(networkType);
Wink Savilleed9c02b2010-12-03 12:01:38 -0800777 if (DBG) log("special network already active");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700778 return Phone.APN_ALREADY_ACTIVE;
779 }
Wink Savilleed9c02b2010-12-03 12:01:38 -0800780 if (DBG) log("special network already connecting");
Robert Greenwalt42acef32009-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 Savilleed9c02b2010-12-03 12:01:38 -0800787 if (DBG) log("reconnecting to special network");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700788 network.reconnect();
789 return Phone.APN_REQUEST_STARTED;
790 } else {
Robert Greenwalt0be1e982010-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 Greenwalt02648a42010-05-18 10:52:51 -0700799 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700800 }
801 }
802 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 }
804
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700805 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700807 enforceChangePermission();
808
Robert Greenwalt9c75d4a2009-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 Ondo3bed4c92011-07-19 11:23:37 -0500816 for (FeatureUser x : mFeatureUsers) {
817 if (x.isSameUser(pid, uid, networkType, feature)) {
818 u = x;
Robert Greenwalt9c75d4a2009-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 Savilleed9c02b2010-12-03 12:01:38 -0800829 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700830 return 1;
831 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700832 }
833
Robert Greenwalt9c75d4a2009-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 Greenwalt42acef32009-08-12 16:08:25 -0700843 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800844 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt42acef32009-08-12 16:08:25 -0700845 ": " + feature);
846 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
849 return -1;
850 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700851
Robert Greenwalt9c75d4a2009-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 Savilleed9c02b2010-12-03 12:01:38 -0800857 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700858 return 1;
859 }
Robert Greenwalt9c75d4a2009-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 Ondo3bed4c92011-07-19 11:23:37 -0500870 for (FeatureUser x : mFeatureUsers) {
871 if (x.isSameUser(u)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800872 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700873 return 1;
874 }
875 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700876 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700877
878 // TODO - move to MobileDataStateTracker
879 int usedNetworkType = networkType;
880 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville9d7d6282011-03-12 14:52:01 -0800881 usedNetworkType = convertFeatureToNetworkType(feature);
882 if (usedNetworkType < 0) {
883 usedNetworkType = networkType;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700884 }
885 }
886 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700887 if (tracker == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800888 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700889 return -1;
890 }
891 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700892 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700893 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -0800894 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700895 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800896 if (DBG) log("not tearing down special network - " +
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700897 "others still using it");
898 return 1;
899 }
900 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -0800901 } else {
902 if (DBG) log("not a known feature - dropping");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700903 }
904 }
Wink Savilleed9c02b2010-12-03 12:01:38 -0800905 if (DBG) log("Doing network teardown");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700906 if (callTeardown) {
907 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700908 return 1;
909 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -0700910 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 }
913
914 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700915 * @deprecated use requestRouteToHostAddress instead
916 *
The Android Open Source Project9066cfe2009-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 Greenwalt86e9e552009-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 Project9066cfe2009-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 Greenwalt585ac0f2010-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 Project9066cfe2009-03-03 19:31:44 -0800945 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -0700946 if (mProtectedNetworks.contains(networkType)) {
947 enforceConnectivityInternalPermission();
948 }
949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
951 return false;
952 }
953 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -0700954
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700955 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
956 tracker.isTeardownRequested()) {
Robert Greenwalt8206ff32009-09-10 15:06:20 -0700957 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800958 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700959 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -0700960 }
961 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700963 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700964 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700965 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -0700966 return addRouteToAddress(lp, addr);
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700967 } catch (UnknownHostException e) {}
968 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700969 }
970
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700971 private boolean addRoute(LinkProperties p, RouteInfo r) {
972 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700973 }
974
Robert Greenwalt0a46db52011-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 Greenwaltad55d352011-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 Greenwalt0a46db52011-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 Greenwalt476f5522011-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 Greenwalt0a46db52011-07-14 14:28:05 -07001018 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-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 Greenwalt0a46db52011-07-14 14:28:05 -07001023 }
Robert Greenwalt476f5522011-07-15 09:45:08 -07001024 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalt0a46db52011-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 Project9066cfe2009-03-03 19:31:44 -08001055 }
1056
1057 /**
1058 * @see ConnectivityManager#getBackgroundDataSetting()
1059 */
1060 public boolean getBackgroundDataSetting() {
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001061 return mBackgroundDataEnabled.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001063
The Android Open Source Project9066cfe2009-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 Greenwalt86e9e552009-07-16 17:21:39 -07001071
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001072 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1073
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001074 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1075 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001078 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwaltdb4afae2011-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 Greenwalt86e9e552009-07-16 17:21:39 -07001084 }
1085
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001086 /**
1087 * @see ConnectivityManager#getMobileDataEnabled()
1088 */
1089 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-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 Greenwaltc03fa502010-02-23 18:58:05 -08001093 enforceAccessPermission();
1094 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1095 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savilleed9c02b2010-12-03 12:01:38 -08001096 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001097 return retVal;
1098 }
1099
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001100 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001101 enforceConnectivityInternalPermission();
1102
Robert Greenwaltd55a6b42011-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 Greenwaltc03fa502010-02-23 18:58:05 -08001116 /**
1117 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1118 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001119 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001120 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001121 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001122
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001123 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001124 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001125 }
1126
1127 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-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 Greenwaltc03fa502010-02-23 18:58:05 -08001131 }
Wink Savillee7982682010-12-07 10:31:02 -08001132 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001133 }
1134 }
1135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001137 mContext.enforceCallingOrSelfPermission(
1138 android.Manifest.permission.ACCESS_NETWORK_STATE,
1139 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 }
1141
1142 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001143 mContext.enforceCallingOrSelfPermission(
1144 android.Manifest.permission.CHANGE_NETWORK_STATE,
1145 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 }
1147
Robert Greenwaltd0e18ff2010-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 Greenwalt2a091d72010-02-11 18:18:40 -08001155 private void enforceTetherAccessPermission() {
1156 mContext.enforceCallingOrSelfPermission(
1157 android.Manifest.permission.ACCESS_NETWORK_STATE,
1158 "ConnectivityService");
1159 }
1160
Robert Greenwalt14f2ef42010-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 Project9066cfe2009-03-03 19:31:44 -08001167 /**
Robert Greenwalt86e9e552009-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 Project9066cfe2009-03-03 19:31:44 -08001172 * @param info the {@code NetworkInfo} for the network
1173 */
1174 private void handleDisconnect(NetworkInfo info) {
1175
Robert Greenwalt42acef32009-08-12 16:08:25 -07001176 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177
Robert Greenwalt42acef32009-08-12 16:08:25 -07001178 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-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 Greenwaltd55a6b42011-03-25 13:09:25 -07001185 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-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 Project9066cfe2009-03-03 19:31:44 -08001193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 }
1195
The Android Open Source Project9066cfe2009-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 Greenwalt86e9e552009-07-16 17:21:39 -07001206 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1207 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001209
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001210 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001211 tryFailover(prevNetType);
1212 if (mActiveDefaultNetwork != -1) {
1213 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001214 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1215 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001216 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001217 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1218 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001219 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001220 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-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 Greenwaltda03c4e2010-01-20 19:29:41 -08001243 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001244 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-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 Greenwaltf21ef7d2011-01-11 13:56:33 -08001251 if (mActiveDefaultNetwork != -1) {
1252 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001253 }
1254 }
1255
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001256 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001257 /*
Robert Greenwaltbff90182011-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 Greenwalt42acef32009-08-12 16:08:25 -07001261 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001262 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001263 if (mActiveDefaultNetwork == prevNetType) {
1264 mActiveDefaultNetwork = -1;
1265 }
1266
Robert Greenwaltf21ef7d2011-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 Greenwaltd55a6b42011-03-25 13:09:25 -07001272// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001273// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001274 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001275 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001276 if (mNetConfigs[checkType] == null) continue;
1277 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville9f7a0b22011-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 Greenwaltd55a6b42011-03-25 13:09:25 -07001289// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001290
Robert Greenwaltf21ef7d2011-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 Greenwalt42acef32009-08-12 16:08:25 -07001296 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001297 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 }
1301
1302 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt1e9aac22010-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 Project9066cfe2009-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 Greenwalt86e9e552009-07-16 17:21:39 -07001321 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1322 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001324 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001325 sendStickyBroadcast(intent);
The Android Open Source Project9066cfe2009-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 Project9066cfe2009-03-03 19:31:44 -08001334
Robert Greenwalt42acef32009-08-12 16:08:25 -07001335 String reason = info.getReason();
1336 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001337
Robert Greenwalt572172b2010-10-08 16:35:52 -07001338 String reasonText;
1339 if (reason == null) {
1340 reasonText = ".";
1341 } else {
1342 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001344 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-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 Greenwaltda03c4e2010-01-20 19:29:41 -08001361
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001362 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001363 tryFailover(info.getType());
1364 if (mActiveDefaultNetwork != -1) {
1365 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001366 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1367 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001368 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001369 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1370 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001371 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001372
Robert Greenwalt029be812010-09-20 18:01:43 -07001373 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001374 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-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 Greenwaltf21ef7d2011-01-11 13:56:33 -08001379 if (mActiveDefaultNetwork != -1) {
1380 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001381 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001382 }
1383
1384 private void sendStickyBroadcast(Intent intent) {
1385 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001386 if (!mSystemReady) {
1387 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001388 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001389 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1390 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001391 }
1392 }
1393
1394 void systemReady() {
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001395 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1396 mNetd = INetworkManagementService.Stub.asInterface(b);
1397
Mike Lockwood0f79b542009-08-14 14:18:49 -04001398 synchronized(this) {
1399 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001400 if (mInitialBroadcast != null) {
1401 mContext.sendStickyBroadcast(mInitialBroadcast);
1402 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001403 }
1404 }
Robert Greenwalt434203a2010-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 Project9066cfe2009-03-03 19:31:44 -08001407 }
1408
1409 private void handleConnect(NetworkInfo info) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001410 int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411
1412 // snapshot isFailover, because sendConnectedBroadcast() resets it
1413 boolean isFailover = info.isFailover();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001414 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415
Robert Greenwalt42acef32009-08-12 16:08:25 -07001416 // if this is a default net and other default is running
1417 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001418 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001419 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1420 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001421 mNetConfigs[mActiveDefaultNetwork].priority >
1422 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001423 mNetworkPreference == mActiveDefaultNetwork) {
1424 // don't accept this one
Wink Savilleed9c02b2010-12-03 12:01:38 -08001425 if (DBG) {
1426 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001427 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001428 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001429 teardown(thisNet);
1430 return;
1431 } else {
1432 // tear down the other
1433 NetworkStateTracker otherNet =
1434 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001435 if (DBG) {
1436 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001437 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001438 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001439 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001440 loge("Network declined teardown request");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001441 return;
1442 }
Robert Greenwalt14f2ef42010-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 Greenwaltf3331232010-09-24 14:32:21 -07001451 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001452 mNetTransitionWakeLockSerialNumber, 0),
1453 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001454 }
1455 }
1456 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-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 Greenwalt42acef32009-08-12 16:08:25 -07001465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001467 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001468 handleConnectivityChange(type, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001469 sendConnectedBroadcast(info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 }
1471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 /**
Robert Greenwaltc76b8fa2010-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 Project9066cfe2009-03-03 19:31:44 -08001477 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001478 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07001479 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001482 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001483 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001485 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001486
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001487 LinkProperties curLp = mCurrentLinkProperties[netType];
1488 LinkProperties newLp = null;
1489
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001490 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001491 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-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 Greenwalt0a46db52011-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 Savillee8222252011-07-13 13:44:13 -07001510 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001511 if (DBG) {
1512 log("handleConnectivityChange: addresses changed" +
1513 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1514 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07001515 }
Robert Greenwalt0a46db52011-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 Savillee8222252011-07-13 13:44:13 -07001522 }
1523 } else {
Robert Greenwalt0a46db52011-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 Savillee8222252011-07-13 13:44:13 -07001528 }
Wink Savillee8222252011-07-13 13:44:13 -07001529 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001530 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07001531 handleApplyDefaultProxy(netType);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001532 }
1533 } else {
Robert Greenwalt0a46db52011-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 Greenwalt42acef32009-08-12 16:08:25 -07001539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001541 mCurrentLinkProperties[netType] = newLp;
1542 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07001543
Wink Savillee8222252011-07-13 13:44:13 -07001544 if (doReset || resetMask != 0) {
Robert Greenwaltec896c62011-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 Savillee8222252011-07-13 13:44:13 -07001549 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1550 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001551 }
1552 }
1553 }
Kazuhiro Ondo1ccb10e2011-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 Project9066cfe2009-03-03 19:31:44 -08001564 }
1565
Robert Greenwalt0a46db52011-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 Greenwaltad55d352011-07-22 11:55:33 -07001575 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1576 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001577 if (curLp != null) {
1578 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07001579 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001580 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001581 } else if (newLp != null) {
1582 routeDiff.added = newLp.getRoutes();
1583 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001584 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001585
Robert Greenwaltad55d352011-07-22 11:55:33 -07001586 for (RouteInfo r : routeDiff.removed) {
1587 if (isLinkDefault || ! r.isDefaultRoute()) {
1588 removeRoute(curLp, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001589 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001590 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001591
Robert Greenwaltad55d352011-07-22 11:55:33 -07001592 for (RouteInfo r : routeDiff.added) {
1593 if (isLinkDefault || ! r.isDefaultRoute()) {
1594 addRoute(newLp, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001595 }
1596 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001597
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001598 if (!isLinkDefault) {
1599 // handle DNS routes
Robert Greenwaltad55d352011-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 Greenwalt0a46db52011-07-14 14:28:05 -07001604 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001605 for (InetAddress newDns : dnsDiff.added) {
1606 addRouteToAddress(newLp, newDns);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001607 }
Robert Greenwaltad55d352011-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 Greenwaltedcb4f92011-03-22 18:47:42 -07001619 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001620 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001621 }
1622 }
1623
1624
Irfan Sheriffd649c122010-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 Savilleed9c02b2010-12-03 12:01:38 -08001635 loge(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-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 Savilleed9c02b2010-12-03 12:01:38 -08001645 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-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 Savilleed9c02b2010-12-03 12:01:38 -08001672 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001673 }
1674 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001675 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-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 Greenwalt42acef32009-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 Savilleed9c02b2010-12-03 12:01:38 -08001703 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001704 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001705 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001706 continue;
1707 }
1708 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001709 if (nt.getNetworkInfo().isConnected() &&
1710 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001711 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001712 if (p == null) continue;
Robert Greenwalt42acef32009-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 Greenwalt47f69fe2010-06-15 15:43:39 -07001717 Collection<InetAddress> dnses = p.getDnses();
1718 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-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 Greenwalt10398722010-12-17 15:20:36 -08001740 // return true if results in a change
1741 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001742 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08001743 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001744 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-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 Greenwalt42acef32009-08-12 16:08:25 -07001750 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001751 return changed;
Robert Greenwalt42acef32009-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 Greenwalt03595d02010-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 Chesnutt3d1db862011-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 Greenwalt03595d02010-11-02 14:08:23 -07001776 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001777 }
1778
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001779 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001780 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001781 NetworkStateTracker nt = mNetTrackers[netType];
1782 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001783 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001784 if (p == null) return;
1785 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt572b7042011-07-25 17:00:13 -07001786 try {
1787 mNetd.setDnsServersForInterface(p.getInterfaceName(),
1788 NetworkUtils.makeStrings(dnses));
1789 } catch (Exception e) {
1790 Slog.e(TAG, "exception setting dns servers: " + e);
1791 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001792 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001793 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt572b7042011-07-25 17:00:13 -07001794 try {
1795 mNetd.setDefaultInterfaceForDns(p.getInterfaceName());
1796 } catch (Exception e) {
1797 Slog.e(TAG, "exception setting default dns interface: " + e);
1798 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001799 int j = 1;
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001800 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001801 String dnsString = mDefaultDns.getHostAddress();
1802 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1803 if (DBG) {
1804 log("no dns provided - using " + dnsString);
1805 }
1806 changed = true;
1807 SystemProperties.set("net.dns1", dnsString);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001808 }
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001809 j++;
1810 } else {
1811 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001812 String dnsString = dns.getHostAddress();
1813 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1814 j++;
1815 continue;
1816 }
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001817 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001818 log("adding dns " + dns + " for " +
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001819 nt.getNetworkInfo().getTypeName());
1820 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001821 changed = true;
1822 SystemProperties.set("net.dns" + j++, dnsString);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001823 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001824 }
1825 for (int k=j ; k<mNumDnsEntries; k++) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001826 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1827 if (DBG) log("erasing net.dns" + k);
1828 changed = true;
1829 SystemProperties.set("net.dns" + k, "");
1830 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001831 }
1832 mNumDnsEntries = j;
1833 } else {
1834 // set per-pid dns for attached secondary nets
1835 List pids = mNetRequestersPids[netType];
1836 for (int y=0; y< pids.size(); y++) {
1837 Integer pid = (Integer)pids.get(y);
Robert Greenwalt10398722010-12-17 15:20:36 -08001838 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 }
1840 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001841 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001843 }
1844
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001845 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001846 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1847 NETWORK_RESTORE_DELAY_PROP_NAME);
1848 if(restoreDefaultNetworkDelayStr != null &&
1849 restoreDefaultNetworkDelayStr.length() != 0) {
1850 try {
1851 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1852 } catch (NumberFormatException e) {
1853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001855 // if the system property isn't set, use the value for the apn type
1856 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1857
1858 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1859 (mNetConfigs[networkType] != null)) {
1860 ret = mNetConfigs[networkType].restoreTime;
1861 }
1862 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 }
1864
1865 @Override
1866 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001867 if (mContext.checkCallingOrSelfPermission(
1868 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001870 pw.println("Permission Denial: can't dump ConnectivityService " +
1871 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1872 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 return;
1874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 pw.println();
1876 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08001877 if (nst != null) {
1878 if (nst.getNetworkInfo().isConnected()) {
1879 pw.println("Active network: " + nst.getNetworkInfo().
1880 getTypeName());
1881 }
1882 pw.println(nst.getNetworkInfo());
1883 pw.println(nst);
1884 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001887
1888 pw.println("Network Requester Pids:");
1889 for (int net : mPriorityList) {
1890 String pidString = net + ": ";
1891 for (Object pid : mNetRequestersPids[net]) {
1892 pidString = pidString + pid.toString() + ", ";
1893 }
1894 pw.println(pidString);
1895 }
1896 pw.println();
1897
1898 pw.println("FeatureUsers:");
1899 for (Object requester : mFeatureUsers) {
1900 pw.println(requester.toString());
1901 }
1902 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001903
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001904 synchronized (this) {
1905 pw.println("NetworkTranstionWakeLock is currently " +
1906 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1907 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1908 }
1909 pw.println();
1910
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001911 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001912
1913 if (mInetLog != null) {
1914 pw.println();
1915 pw.println("Inet condition reports:");
1916 for(int i = 0; i < mInetLog.size(); i++) {
1917 pw.println(mInetLog.get(i));
1918 }
1919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 }
1921
Robert Greenwalt42acef32009-08-12 16:08:25 -07001922 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07001924 public MyHandler(Looper looper) {
1925 super(looper);
1926 }
1927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 @Override
1929 public void handleMessage(Message msg) {
1930 NetworkInfo info;
1931 switch (msg.what) {
1932 case NetworkStateTracker.EVENT_STATE_CHANGED:
1933 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08001934 int type = info.getType();
1935 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08001936
Wink Savilleed9c02b2010-12-03 12:01:38 -08001937 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001938 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08001939 state + "/" + info.getDetailedState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940
1941 // Connectivity state changed:
1942 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001943 // [12-9] Network subtype (for mobile network, as defined
1944 // by TelephonyManager)
1945 // [8-3] Detailed state ordinal (as defined by
1946 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 // [2-0] Network type (as defined by ConnectivityManager)
1948 int eventLogParam = (info.getType() & 0x7) |
1949 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1950 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001951 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001952 eventLogParam);
1953
1954 if (info.getDetailedState() ==
1955 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08001957 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08001959 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001961 // the logic here is, handle SUSPENDED the same as
1962 // DISCONNECTED. The only difference being we are
1963 // broadcasting an intent with NetworkInfo that's
1964 // suspended. This allows the applications an
1965 // opportunity to handle DISCONNECTED and SUSPENDED
1966 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08001968 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 handleConnect(info);
1970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001973 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001974 // TODO: Temporary allowing network configuration
1975 // change not resetting sockets.
1976 // @see bug/4455071
1977 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07001979 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001980 String causedBy = null;
1981 synchronized (ConnectivityService.this) {
1982 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
1983 mNetTransitionWakeLock.isHeld()) {
1984 mNetTransitionWakeLock.release();
1985 causedBy = mNetTransitionWakeLockCausedBy;
1986 }
1987 }
1988 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001989 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001990 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07001991 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001992 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001993 FeatureUser u = (FeatureUser)msg.obj;
1994 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001995 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001996 case EVENT_INET_CONDITION_CHANGE:
1997 {
1998 int netType = msg.arg1;
1999 int condition = msg.arg2;
2000 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002001 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002002 }
2003 case EVENT_INET_CONDITION_HOLD_END:
2004 {
2005 int netType = msg.arg1;
2006 int sequence = msg.arg2;
2007 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002008 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002009 }
2010 case EVENT_SET_NETWORK_PREFERENCE:
2011 {
2012 int preference = msg.arg1;
2013 handleSetNetworkPreference(preference);
2014 break;
2015 }
2016 case EVENT_SET_BACKGROUND_DATA:
2017 {
2018 boolean enabled = (msg.arg1 == ENABLED);
2019 handleSetBackgroundData(enabled);
2020 break;
2021 }
2022 case EVENT_SET_MOBILE_DATA:
2023 {
2024 boolean enabled = (msg.arg1 == ENABLED);
2025 handleSetMobileData(enabled);
2026 break;
2027 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002028 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2029 {
2030 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002031 break;
2032 }
2033 case EVENT_SET_DEPENDENCY_MET:
2034 {
2035 boolean met = (msg.arg1 == ENABLED);
2036 handleSetDependencyMet(msg.arg2, met);
2037 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 }
2040 }
2041 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002042
2043 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002044 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002045 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002046
2047 if (isTetheringSupported()) {
2048 return mTethering.tether(iface);
2049 } else {
2050 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2051 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002052 }
2053
2054 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002055 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002056 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002057
2058 if (isTetheringSupported()) {
2059 return mTethering.untether(iface);
2060 } else {
2061 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2062 }
2063 }
2064
2065 // javadoc from interface
2066 public int getLastTetherError(String iface) {
2067 enforceTetherAccessPermission();
2068
2069 if (isTetheringSupported()) {
2070 return mTethering.getLastTetherError(iface);
2071 } else {
2072 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2073 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002074 }
2075
2076 // TODO - proper iface API for selection by property, inspection, etc
2077 public String[] getTetherableUsbRegexs() {
2078 enforceTetherAccessPermission();
2079 if (isTetheringSupported()) {
2080 return mTethering.getTetherableUsbRegexs();
2081 } else {
2082 return new String[0];
2083 }
2084 }
2085
2086 public String[] getTetherableWifiRegexs() {
2087 enforceTetherAccessPermission();
2088 if (isTetheringSupported()) {
2089 return mTethering.getTetherableWifiRegexs();
2090 } else {
2091 return new String[0];
2092 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002093 }
2094
Danica Chang6fdd0c62010-08-11 14:54:43 -07002095 public String[] getTetherableBluetoothRegexs() {
2096 enforceTetherAccessPermission();
2097 if (isTetheringSupported()) {
2098 return mTethering.getTetherableBluetoothRegexs();
2099 } else {
2100 return new String[0];
2101 }
2102 }
2103
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002104 // TODO - move iface listing, queries, etc to new module
2105 // javadoc from interface
2106 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002107 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002108 return mTethering.getTetherableIfaces();
2109 }
2110
2111 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002112 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002113 return mTethering.getTetheredIfaces();
2114 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002115
Robert Greenwalt5a735062010-03-02 17:25:02 -08002116 public String[] getTetheringErroredIfaces() {
2117 enforceTetherAccessPermission();
2118 return mTethering.getErroredIfaces();
2119 }
2120
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002121 // if ro.tether.denied = true we default to no tethering
2122 // gservices could set the secure setting to 1 though to enable it on a build where it
2123 // had previously been turned off.
2124 public boolean isTetheringSupported() {
2125 enforceTetherAccessPermission();
2126 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002127 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2128 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2129 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002130 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002131
2132 // An API NetworkStateTrackers can call when they lose their network.
2133 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2134 // whichever happens first. The timer is started by the first caller and not
2135 // restarted by subsequent callers.
2136 public void requestNetworkTransitionWakelock(String forWhom) {
2137 enforceConnectivityInternalPermission();
2138 synchronized (this) {
2139 if (mNetTransitionWakeLock.isHeld()) return;
2140 mNetTransitionWakeLockSerialNumber++;
2141 mNetTransitionWakeLock.acquire();
2142 mNetTransitionWakeLockCausedBy = forWhom;
2143 }
2144 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002145 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002146 mNetTransitionWakeLockSerialNumber, 0),
2147 mNetTransitionWakeLockTimeout);
2148 return;
2149 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002150
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002151 // 100 percent is full good, 0 is full bad.
2152 public void reportInetCondition(int networkType, int percentage) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002153 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002154 mContext.enforceCallingOrSelfPermission(
2155 android.Manifest.permission.STATUS_BAR,
2156 "ConnectivityService");
2157
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002158 if (DBG) {
2159 int pid = getCallingPid();
2160 int uid = getCallingUid();
2161 String s = pid + "(" + uid + ") reports inet is " +
2162 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2163 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2164 mInetLog.add(s);
2165 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2166 mInetLog.remove(0);
2167 }
2168 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002169 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002170 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2171 }
2172
2173 private void handleInetConditionChange(int netType, int condition) {
2174 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002175 log("Inet connectivity change, net=" +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002176 netType + ", condition=" + condition +
2177 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2178 }
2179 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002180 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002181 return;
2182 }
2183 if (mActiveDefaultNetwork != netType) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002184 if (DBG) log("given net not default - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002185 return;
2186 }
2187 mDefaultInetCondition = condition;
2188 int delay;
2189 if (mInetConditionChangeInFlight == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002190 if (DBG) log("starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002191 // setup a new hold to debounce this
2192 if (mDefaultInetCondition > 50) {
2193 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2194 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2195 } else {
2196 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2197 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2198 }
2199 mInetConditionChangeInFlight = true;
2200 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2201 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2202 } else {
2203 // we've set the new condition, when this hold ends that will get
2204 // picked up
Wink Savilleed9c02b2010-12-03 12:01:38 -08002205 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002206 }
2207 }
2208
2209 private void handleInetConditionHoldEnd(int netType, int sequence) {
2210 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002211 log("Inet hold end, net=" + netType +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002212 ", condition =" + mDefaultInetCondition +
2213 ", published condition =" + mDefaultInetConditionPublished);
2214 }
2215 mInetConditionChangeInFlight = false;
2216
2217 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002218 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002219 return;
2220 }
2221 if (mDefaultConnectionSequence != sequence) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002222 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002223 return;
2224 }
2225 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002226 if (DBG) log("no change in condition - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002227 return;
2228 }
2229 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2230 if (networkInfo.isConnected() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002231 if (DBG) log("default network not connected - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002232 return;
2233 }
2234 mDefaultInetConditionPublished = mDefaultInetCondition;
2235 sendInetConditionBroadcast(networkInfo);
2236 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002237 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002238
2239 public synchronized ProxyProperties getProxy() {
2240 if (mGlobalProxy != null) return mGlobalProxy;
2241 if (mDefaultProxy != null) return mDefaultProxy;
2242 return null;
2243 }
2244
2245 public void setGlobalProxy(ProxyProperties proxyProperties) {
2246 enforceChangePermission();
2247 synchronized (mGlobalProxyLock) {
2248 if (proxyProperties == mGlobalProxy) return;
2249 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2250 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2251
2252 String host = "";
2253 int port = 0;
2254 String exclList = "";
2255 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2256 mGlobalProxy = new ProxyProperties(proxyProperties);
2257 host = mGlobalProxy.getHost();
2258 port = mGlobalProxy.getPort();
2259 exclList = mGlobalProxy.getExclusionList();
2260 } else {
2261 mGlobalProxy = null;
2262 }
2263 ContentResolver res = mContext.getContentResolver();
2264 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2265 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002266 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002267 exclList);
2268 }
2269
2270 if (mGlobalProxy == null) {
2271 proxyProperties = mDefaultProxy;
2272 }
2273 sendProxyBroadcast(proxyProperties);
2274 }
2275
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002276 private void loadGlobalProxy() {
2277 ContentResolver res = mContext.getContentResolver();
2278 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2279 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2280 String exclList = Settings.Secure.getString(res,
2281 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2282 if (!TextUtils.isEmpty(host)) {
2283 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2284 synchronized (mGlobalProxyLock) {
2285 mGlobalProxy = proxyProperties;
2286 }
2287 }
2288 }
2289
Robert Greenwalt434203a2010-10-11 16:00:27 -07002290 public ProxyProperties getGlobalProxy() {
2291 synchronized (mGlobalProxyLock) {
2292 return mGlobalProxy;
2293 }
2294 }
2295
2296 private void handleApplyDefaultProxy(int type) {
2297 // check if new default - push it out to all VM if so
2298 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2299 synchronized (this) {
2300 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2301 if (mDefaultProxy == proxy) return;
Robert Greenwaltfde1eb72011-07-29 10:03:37 -07002302 if (proxy != null && !TextUtils.isEmpty(proxy.getHost())) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002303 mDefaultProxy = proxy;
2304 } else {
2305 mDefaultProxy = null;
2306 }
2307 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002308 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002309 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2310 if (mGlobalProxy != null) return;
2311 sendProxyBroadcast(proxy);
2312 }
2313
2314 private void handleDeprecatedGlobalHttpProxy() {
2315 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2316 Settings.Secure.HTTP_PROXY);
2317 if (!TextUtils.isEmpty(proxy)) {
2318 String data[] = proxy.split(":");
2319 String proxyHost = data[0];
2320 int proxyPort = 8080;
2321 if (data.length > 1) {
2322 try {
2323 proxyPort = Integer.parseInt(data[1]);
2324 } catch (NumberFormatException e) {
2325 return;
2326 }
2327 }
2328 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2329 setGlobalProxy(p);
2330 }
2331 }
2332
2333 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002334 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002335 log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002336 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002337 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2338 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002339 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002340 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002341 }
2342
2343 private static class SettingsObserver extends ContentObserver {
2344 private int mWhat;
2345 private Handler mHandler;
2346 SettingsObserver(Handler handler, int what) {
2347 super(handler);
2348 mHandler = handler;
2349 mWhat = what;
2350 }
2351
2352 void observe(Context context) {
2353 ContentResolver resolver = context.getContentResolver();
2354 resolver.registerContentObserver(Settings.Secure.getUriFor(
2355 Settings.Secure.HTTP_PROXY), false, this);
2356 }
2357
2358 @Override
2359 public void onChange(boolean selfChange) {
2360 mHandler.obtainMessage(mWhat).sendToTarget();
2361 }
2362 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002363
2364 private void log(String s) {
2365 Slog.d(TAG, s);
2366 }
2367
2368 private void loge(String s) {
2369 Slog.e(TAG, s);
2370 }
Wink Saville9d7d6282011-03-12 14:52:01 -08002371 int convertFeatureToNetworkType(String feature){
2372 int networkType = -1;
2373 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2374 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2375 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2376 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2377 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2378 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2379 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2380 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2381 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2382 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2383 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2384 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2385 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2386 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2387 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2388 }
2389 return networkType;
2390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391}