blob: 2bbf92e2bb7e4f8a745d25cb7fc229ab98871ae2 [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();
966 return addRoute(lp, RouteInfo.makeHostRoute(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
979 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
980 boolean doAdd) {
981 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
982
983 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
984 loge("Error adding route - too much recursion");
985 return false;
986 }
987
988 if (r.isHostRoute() == false) {
989 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
990 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -0700991 if (bestRoute.getGateway().equals(r.getGateway())) {
992 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700993 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-07-15 09:45:08 -0700994 } else {
995 // if we will connect to our gateway through another route, add a direct
996 // route to it's gateway
997 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700998 }
Robert Greenwalt476f5522011-07-15 09:45:08 -0700999 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001000 }
1001 }
1002 if (doAdd) {
1003 if (DBG) log("Adding " + r + " for interface " + ifaceName);
1004 mAddedRoutes.add(r);
1005 try {
1006 mNetd.addRoute(ifaceName, r);
1007 } catch (Exception e) {
1008 // never crash - catch them all
1009 loge("Exception trying to add a route: " + e);
1010 return false;
1011 }
1012 } else {
1013 // if we remove this one and there are no more like it, then refcount==0 and
1014 // we can remove it from the table
1015 mAddedRoutes.remove(r);
1016 if (mAddedRoutes.contains(r) == false) {
1017 if (DBG) log("Removing " + r + " for interface " + ifaceName);
1018 try {
1019 mNetd.removeRoute(ifaceName, r);
1020 } catch (Exception e) {
1021 // never crash - catch them all
1022 loge("Exception trying to remove a route: " + e);
1023 return false;
1024 }
1025 } else {
1026 if (DBG) log("not removing " + r + " as it's still in use");
1027 }
1028 }
1029 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 }
1031
1032 /**
1033 * @see ConnectivityManager#getBackgroundDataSetting()
1034 */
1035 public boolean getBackgroundDataSetting() {
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001036 return mBackgroundDataEnabled.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 /**
1040 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1041 */
1042 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1043 mContext.enforceCallingOrSelfPermission(
1044 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1045 "ConnectivityService");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001046
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001047 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1048
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001049 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1050 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001053 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwaltdb4afae2011-02-25 13:44:09 -08001054 Settings.Secure.putInt(mContext.getContentResolver(),
1055 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1056 Intent broadcast = new Intent(
1057 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1058 mContext.sendBroadcast(broadcast);
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001059 }
1060
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001061 /**
1062 * @see ConnectivityManager#getMobileDataEnabled()
1063 */
1064 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001065 // TODO: This detail should probably be in DataConnectionTracker's
1066 // which is where we store the value and maybe make this
1067 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001068 enforceAccessPermission();
1069 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1070 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savilleed9c02b2010-12-03 12:01:38 -08001071 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001072 return retVal;
1073 }
1074
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001075 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001076 enforceConnectivityInternalPermission();
1077
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001078 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1079 (met ? ENABLED : DISABLED), networkType));
1080 }
1081
1082 private void handleSetDependencyMet(int networkType, boolean met) {
1083 if (mNetTrackers[networkType] != null) {
1084 if (DBG) {
1085 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1086 }
1087 mNetTrackers[networkType].setDependencyMet(met);
1088 }
1089 }
1090
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001091 /**
1092 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1093 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001094 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001095 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001096 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001097
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001098 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001099 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001100 }
1101
1102 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001103 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1104 if (DBG) {
1105 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001106 }
Wink Savillee7982682010-12-07 10:31:02 -08001107 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001108 }
1109 }
1110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001112 mContext.enforceCallingOrSelfPermission(
1113 android.Manifest.permission.ACCESS_NETWORK_STATE,
1114 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
1116
1117 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001118 mContext.enforceCallingOrSelfPermission(
1119 android.Manifest.permission.CHANGE_NETWORK_STATE,
1120 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 }
1122
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001123 // TODO Make this a special check when it goes public
1124 private void enforceTetherChangePermission() {
1125 mContext.enforceCallingOrSelfPermission(
1126 android.Manifest.permission.CHANGE_NETWORK_STATE,
1127 "ConnectivityService");
1128 }
1129
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001130 private void enforceTetherAccessPermission() {
1131 mContext.enforceCallingOrSelfPermission(
1132 android.Manifest.permission.ACCESS_NETWORK_STATE,
1133 "ConnectivityService");
1134 }
1135
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001136 private void enforceConnectivityInternalPermission() {
1137 mContext.enforceCallingOrSelfPermission(
1138 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1139 "ConnectivityService");
1140 }
1141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001143 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1144 * network, we ignore it. If it is for the active network, we send out a
1145 * broadcast. But first, we check whether it might be possible to connect
1146 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 * @param info the {@code NetworkInfo} for the network
1148 */
1149 private void handleDisconnect(NetworkInfo info) {
1150
Robert Greenwalt42acef32009-08-12 16:08:25 -07001151 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152
Robert Greenwalt42acef32009-08-12 16:08:25 -07001153 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 /*
1155 * If the disconnected network is not the active one, then don't report
1156 * this as a loss of connectivity. What probably happened is that we're
1157 * getting the disconnect for a network that we explicitly disabled
1158 * in accordance with network preference policies.
1159 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001160 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001161 List pids = mNetRequestersPids[prevNetType];
1162 for (int i = 0; i<pids.size(); i++) {
1163 Integer pid = (Integer)pids.get(i);
1164 // will remove them because the net's no longer connected
1165 // need to do this now as only now do we know the pids and
1166 // can properly null things that are no longer referenced.
1167 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 }
1170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1172 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1173 if (info.isFailover()) {
1174 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1175 info.setFailover(false);
1176 }
1177 if (info.getReason() != null) {
1178 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1179 }
1180 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001181 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1182 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001184
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001185 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001186 tryFailover(prevNetType);
1187 if (mActiveDefaultNetwork != -1) {
1188 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001189 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1190 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001191 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001192 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1193 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001194 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001195 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001196
1197 // Reset interface if no other connections are using the same interface
1198 boolean doReset = true;
1199 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1200 if (linkProperties != null) {
1201 String oldIface = linkProperties.getInterfaceName();
1202 if (TextUtils.isEmpty(oldIface) == false) {
1203 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1204 if (networkStateTracker == null) continue;
1205 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1206 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1207 LinkProperties l = networkStateTracker.getLinkProperties();
1208 if (l == null) continue;
1209 if (oldIface.equals(l.getInterfaceName())) {
1210 doReset = false;
1211 break;
1212 }
1213 }
1214 }
1215 }
1216 }
1217
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001218 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001219 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001220
1221 sendStickyBroadcast(intent);
1222 /*
1223 * If the failover network is already connected, then immediately send
1224 * out a followup broadcast indicating successful failover
1225 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001226 if (mActiveDefaultNetwork != -1) {
1227 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001228 }
1229 }
1230
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001231 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001232 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001233 * If this is a default network, check if other defaults are available.
1234 * Try to reconnect on all available and let them hash it out when
1235 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001236 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001237 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001238 if (mActiveDefaultNetwork == prevNetType) {
1239 mActiveDefaultNetwork = -1;
1240 }
1241
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001242 // don't signal a reconnect for anything lower or equal priority than our
1243 // current connected default
1244 // TODO - don't filter by priority now - nice optimization but risky
1245// int currentPriority = -1;
1246// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001247// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001248// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001249 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001250 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001251 if (mNetConfigs[checkType] == null) continue;
1252 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001253
1254// Enabling the isAvailable() optimization caused mobile to not get
1255// selected if it was in the middle of error handling. Specifically
1256// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1257// would not be available and we wouldn't get connected to anything.
1258// So removing the isAvailable() optimization below for now. TODO: This
1259// optimization should work and we need to investigate why it doesn't work.
1260// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1261// complete before it is really complete.
1262// if (!mNetTrackers[checkType].isAvailable()) continue;
1263
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001264// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001265
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001266 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1267 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1268 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1269 checkInfo.setFailover(true);
1270 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001271 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001272 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 }
1276
1277 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001278 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1279 }
1280
1281 private void sendInetConditionBroadcast(NetworkInfo info) {
1282 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1283 }
1284
1285 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1286 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1288 if (info.isFailover()) {
1289 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1290 info.setFailover(false);
1291 }
1292 if (info.getReason() != null) {
1293 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1294 }
1295 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001296 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1297 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001299 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001300 sendStickyBroadcast(intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 }
1302
1303 /**
1304 * Called when an attempt to fail over to another network has failed.
1305 * @param info the {@link NetworkInfo} for the failed network
1306 */
1307 private void handleConnectionFailure(NetworkInfo info) {
1308 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309
Robert Greenwalt42acef32009-08-12 16:08:25 -07001310 String reason = info.getReason();
1311 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001312
Robert Greenwalt572172b2010-10-08 16:35:52 -07001313 String reasonText;
1314 if (reason == null) {
1315 reasonText = ".";
1316 } else {
1317 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001319 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001320
1321 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1322 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1323 if (getActiveNetworkInfo() == null) {
1324 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1325 }
1326 if (reason != null) {
1327 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1328 }
1329 if (extraInfo != null) {
1330 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1331 }
1332 if (info.isFailover()) {
1333 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1334 info.setFailover(false);
1335 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001336
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001337 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001338 tryFailover(info.getType());
1339 if (mActiveDefaultNetwork != -1) {
1340 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001341 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1342 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001343 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001344 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1345 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001346 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001347
Robert Greenwalt029be812010-09-20 18:01:43 -07001348 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001349 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001350 /*
1351 * If the failover network is already connected, then immediately send
1352 * out a followup broadcast indicating successful failover
1353 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001354 if (mActiveDefaultNetwork != -1) {
1355 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001356 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001357 }
1358
1359 private void sendStickyBroadcast(Intent intent) {
1360 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001361 if (!mSystemReady) {
1362 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001363 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001364 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1365 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001366 }
1367 }
1368
1369 void systemReady() {
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001370 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1371 mNetd = INetworkManagementService.Stub.asInterface(b);
1372
Mike Lockwood0f79b542009-08-14 14:18:49 -04001373 synchronized(this) {
1374 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001375 if (mInitialBroadcast != null) {
1376 mContext.sendStickyBroadcast(mInitialBroadcast);
1377 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001378 }
1379 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001380 // load the global proxy at startup
1381 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 }
1383
1384 private void handleConnect(NetworkInfo info) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001385 int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386
1387 // snapshot isFailover, because sendConnectedBroadcast() resets it
1388 boolean isFailover = info.isFailover();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001389 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390
Robert Greenwalt42acef32009-08-12 16:08:25 -07001391 // if this is a default net and other default is running
1392 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001393 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001394 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1395 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001396 mNetConfigs[mActiveDefaultNetwork].priority >
1397 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001398 mNetworkPreference == mActiveDefaultNetwork) {
1399 // don't accept this one
Wink Savilleed9c02b2010-12-03 12:01:38 -08001400 if (DBG) {
1401 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001402 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001403 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001404 teardown(thisNet);
1405 return;
1406 } else {
1407 // tear down the other
1408 NetworkStateTracker otherNet =
1409 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001410 if (DBG) {
1411 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001412 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001413 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001414 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001415 loge("Network declined teardown request");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001416 return;
1417 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001418 }
1419 }
1420 synchronized (ConnectivityService.this) {
1421 // have a new default network, release the transition wakelock in a second
1422 // if it's held. The second pause is to allow apps to reconnect over the
1423 // new network
1424 if (mNetTransitionWakeLock.isHeld()) {
1425 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001426 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001427 mNetTransitionWakeLockSerialNumber, 0),
1428 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001429 }
1430 }
1431 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001432 // this will cause us to come up initially as unconnected and switching
1433 // to connected after our normal pause unless somebody reports us as reall
1434 // disconnected
1435 mDefaultInetConditionPublished = 0;
1436 mDefaultConnectionSequence++;
1437 mInetConditionChangeInFlight = false;
1438 // Don't do this - if we never sign in stay, grey
1439 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001442 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001443 handleConnectivityChange(type, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001444 sendConnectedBroadcast(info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 }
1446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001448 * After a change in the connectivity state of a network. We're mainly
1449 * concerned with making sure that the list of DNS servers is set up
1450 * according to which networks are connected, and ensuring that the
1451 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001453 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07001454 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001457 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001458 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001460 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001461
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001462 LinkProperties curLp = mCurrentLinkProperties[netType];
1463 LinkProperties newLp = null;
1464
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001465 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001466 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07001467 if (VDBG) {
1468 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1469 " doReset=" + doReset + " resetMask=" + resetMask +
1470 "\n curLp=" + curLp +
1471 "\n newLp=" + newLp);
1472 }
1473
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001474 if (curLp != null) {
1475 if (curLp.isIdenticalInterfaceName(newLp)) {
1476 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1477 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1478 for (LinkAddress linkAddr : car.removed) {
1479 if (linkAddr.getAddress() instanceof Inet4Address) {
1480 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1481 }
1482 if (linkAddr.getAddress() instanceof Inet6Address) {
1483 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1484 }
Wink Savillee8222252011-07-13 13:44:13 -07001485 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001486 if (DBG) {
1487 log("handleConnectivityChange: addresses changed" +
1488 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1489 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07001490 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001491 } else {
1492 if (DBG) {
1493 log("handleConnectivityChange: address are the same reset per doReset" +
1494 " linkProperty[" + netType + "]:" +
1495 " resetMask=" + resetMask);
1496 }
Wink Savillee8222252011-07-13 13:44:13 -07001497 }
1498 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001499 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
1500 log("handleConnectivityChange: interface not not equivalent reset both" +
1501 " linkProperty[" + netType + "]:" +
1502 " resetMask=" + resetMask);
Wink Savillee8222252011-07-13 13:44:13 -07001503 }
Wink Savillee8222252011-07-13 13:44:13 -07001504 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001505 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07001506 handleApplyDefaultProxy(netType);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001507 }
1508 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001509 if (VDBG) {
1510 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1511 " doReset=" + doReset + " resetMask=" + resetMask +
1512 "\n curLp=" + curLp +
1513 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001516 mCurrentLinkProperties[netType] = newLp;
1517 updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07001518
Wink Savillee8222252011-07-13 13:44:13 -07001519 if (doReset || resetMask != 0) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07001520 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1521 if (linkProperties != null) {
1522 String iface = linkProperties.getInterfaceName();
1523 if (TextUtils.isEmpty(iface) == false) {
Wink Savillee8222252011-07-13 13:44:13 -07001524 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1525 NetworkUtils.resetConnections(iface, resetMask);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001526 }
1527 }
1528 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001529
1530 // TODO: Temporary notifying upstread change to Tethering.
1531 // @see bug/4455071
1532 /** Notify TetheringService if interface name has been changed. */
1533 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1534 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1535 if (isTetheringSupported()) {
1536 mTethering.handleTetherIfaceChange();
1537 }
1538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001541 /**
1542 * Add and remove routes using the old properties (null if not previously connected),
1543 * new properties (null if becoming disconnected). May even be double null, which
1544 * is a noop.
1545 * Uses isLinkDefault to determine if default routes should be set or conversely if
1546 * host routes should be set to the dns servers
1547 */
1548 private void updateRoutes(LinkProperties newLp, LinkProperties curLp, boolean isLinkDefault) {
1549 Collection<RouteInfo> routesToAdd = null;
1550 CompareResult<InetAddress> dnsDiff = null;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001551
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001552 if (curLp != null) {
1553 // check for the delta between the current set and the new
1554 CompareResult<RouteInfo> routeDiff = curLp.compareRoutes(newLp);
1555 dnsDiff = curLp.compareDnses(newLp);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001556
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001557 for (RouteInfo r : routeDiff.removed) {
1558 if (isLinkDefault || ! r.isDefaultRoute()) {
1559 removeRoute(curLp, r);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001560 }
1561 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001562 routesToAdd = routeDiff.added;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001563 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001564
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001565 if (newLp != null) {
1566 // if we didn't get a diff from cur -> new, then just use the new
1567 if (routesToAdd == null) {
1568 routesToAdd = newLp.getRoutes();
1569 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001570
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001571 for (RouteInfo r : routesToAdd) {
1572 if (isLinkDefault || ! r.isDefaultRoute()) {
1573 addRoute(newLp, r);
1574 }
1575 }
1576 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001577
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001578 if (!isLinkDefault) {
1579 // handle DNS routes
1580 Collection<InetAddress> dnsToAdd = null;
1581 if (dnsDiff != null) {
1582 dnsToAdd = dnsDiff.added;
1583 for (InetAddress dnsAddress : dnsDiff.removed) {
1584 removeRoute(curLp, RouteInfo.makeHostRoute(dnsAddress));
1585 }
1586 }
1587 if (newLp != null) {
1588 if (dnsToAdd == null) {
1589 dnsToAdd = newLp.getDnses();
1590 }
1591 for(InetAddress dnsAddress : dnsToAdd) {
1592 addRoute(newLp, RouteInfo.makeHostRoute(dnsAddress));
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07001593 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001594 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001595 }
1596 }
1597
1598
Irfan Sheriffd649c122010-06-09 15:39:36 -07001599 /**
1600 * Reads the network specific TCP buffer sizes from SystemProperties
1601 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1602 * wide use
1603 */
1604 public void updateNetworkSettings(NetworkStateTracker nt) {
1605 String key = nt.getTcpBufferSizesPropName();
1606 String bufferSizes = SystemProperties.get(key);
1607
1608 if (bufferSizes.length() == 0) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001609 loge(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07001610
1611 // Setting to default values so we won't be stuck to previous values
1612 key = "net.tcp.buffersize.default";
1613 bufferSizes = SystemProperties.get(key);
1614 }
1615
1616 // Set values in kernel
1617 if (bufferSizes.length() != 0) {
1618 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001619 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07001620 + "] which comes from [" + key + "]");
1621 }
1622 setBufferSize(bufferSizes);
1623 }
1624 }
1625
1626 /**
1627 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1628 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1629 *
1630 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1631 * writeMin, writeInitial, writeMax"
1632 */
1633 private void setBufferSize(String bufferSizes) {
1634 try {
1635 String[] values = bufferSizes.split(",");
1636
1637 if (values.length == 6) {
1638 final String prefix = "/sys/kernel/ipv4/tcp_";
1639 stringToFile(prefix + "rmem_min", values[0]);
1640 stringToFile(prefix + "rmem_def", values[1]);
1641 stringToFile(prefix + "rmem_max", values[2]);
1642 stringToFile(prefix + "wmem_min", values[3]);
1643 stringToFile(prefix + "wmem_def", values[4]);
1644 stringToFile(prefix + "wmem_max", values[5]);
1645 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001646 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001647 }
1648 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001649 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001650 }
1651 }
1652
1653 /**
1654 * Writes string to file. Basically same as "echo -n $string > $filename"
1655 *
1656 * @param filename
1657 * @param string
1658 * @throws IOException
1659 */
1660 private void stringToFile(String filename, String string) throws IOException {
1661 FileWriter out = new FileWriter(filename);
1662 try {
1663 out.write(string);
1664 } finally {
1665 out.close();
1666 }
1667 }
1668
1669
Robert Greenwalt42acef32009-08-12 16:08:25 -07001670 /**
1671 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1672 * on the highest priority active net which this process requested.
1673 * If there aren't any, clear it out
1674 */
1675 private void reassessPidDns(int myPid, boolean doBump)
1676 {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001677 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001678 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001679 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001680 continue;
1681 }
1682 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001683 if (nt.getNetworkInfo().isConnected() &&
1684 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001685 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001686 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001687 List pids = mNetRequestersPids[i];
1688 for (int j=0; j<pids.size(); j++) {
1689 Integer pid = (Integer)pids.get(j);
1690 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001691 Collection<InetAddress> dnses = p.getDnses();
1692 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001693 if (doBump) {
1694 bumpDns();
1695 }
1696 return;
1697 }
1698 }
1699 }
1700 }
1701 // nothing found - delete
1702 for (int i = 1; ; i++) {
1703 String prop = "net.dns" + i + "." + myPid;
1704 if (SystemProperties.get(prop).length() == 0) {
1705 if (doBump) {
1706 bumpDns();
1707 }
1708 return;
1709 }
1710 SystemProperties.set(prop, "");
1711 }
1712 }
1713
Robert Greenwalt10398722010-12-17 15:20:36 -08001714 // return true if results in a change
1715 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001716 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08001717 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001718 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001719 String dnsString = dns.getHostAddress();
1720 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1721 changed = true;
1722 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1723 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001724 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001725 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001726 }
1727
1728 private void bumpDns() {
1729 /*
1730 * Bump the property that tells the name resolver library to reread
1731 * the DNS server list from the properties.
1732 */
1733 String propVal = SystemProperties.get("net.dnschange");
1734 int n = 0;
1735 if (propVal.length() != 0) {
1736 try {
1737 n = Integer.parseInt(propVal);
1738 } catch (NumberFormatException e) {}
1739 }
1740 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07001741 /*
1742 * Tell the VMs to toss their DNS caches
1743 */
1744 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1745 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001746 /*
1747 * Connectivity events can happen before boot has completed ...
1748 */
1749 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07001750 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001751 }
1752
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001753 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001754 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001755 NetworkStateTracker nt = mNetTrackers[netType];
1756 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001757 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001758 if (p == null) return;
1759 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08001760 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001761 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001762 int j = 1;
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001763 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001764 String dnsString = mDefaultDns.getHostAddress();
1765 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1766 if (DBG) {
1767 log("no dns provided - using " + dnsString);
1768 }
1769 changed = true;
1770 SystemProperties.set("net.dns1", dnsString);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001771 }
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001772 j++;
1773 } else {
1774 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001775 String dnsString = dns.getHostAddress();
1776 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1777 j++;
1778 continue;
1779 }
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001780 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001781 log("adding dns " + dns + " for " +
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001782 nt.getNetworkInfo().getTypeName());
1783 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001784 changed = true;
1785 SystemProperties.set("net.dns" + j++, dnsString);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001786 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001787 }
1788 for (int k=j ; k<mNumDnsEntries; k++) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001789 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1790 if (DBG) log("erasing net.dns" + k);
1791 changed = true;
1792 SystemProperties.set("net.dns" + k, "");
1793 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001794 }
1795 mNumDnsEntries = j;
1796 } else {
1797 // set per-pid dns for attached secondary nets
1798 List pids = mNetRequestersPids[netType];
1799 for (int y=0; y< pids.size(); y++) {
1800 Integer pid = (Integer)pids.get(y);
Robert Greenwalt10398722010-12-17 15:20:36 -08001801 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 }
1803 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001804 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001806 }
1807
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001808 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001809 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1810 NETWORK_RESTORE_DELAY_PROP_NAME);
1811 if(restoreDefaultNetworkDelayStr != null &&
1812 restoreDefaultNetworkDelayStr.length() != 0) {
1813 try {
1814 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1815 } catch (NumberFormatException e) {
1816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001818 // if the system property isn't set, use the value for the apn type
1819 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1820
1821 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1822 (mNetConfigs[networkType] != null)) {
1823 ret = mNetConfigs[networkType].restoreTime;
1824 }
1825 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827
1828 @Override
1829 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001830 if (mContext.checkCallingOrSelfPermission(
1831 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001833 pw.println("Permission Denial: can't dump ConnectivityService " +
1834 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1835 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 return;
1837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 pw.println();
1839 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08001840 if (nst != null) {
1841 if (nst.getNetworkInfo().isConnected()) {
1842 pw.println("Active network: " + nst.getNetworkInfo().
1843 getTypeName());
1844 }
1845 pw.println(nst.getNetworkInfo());
1846 pw.println(nst);
1847 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001850
1851 pw.println("Network Requester Pids:");
1852 for (int net : mPriorityList) {
1853 String pidString = net + ": ";
1854 for (Object pid : mNetRequestersPids[net]) {
1855 pidString = pidString + pid.toString() + ", ";
1856 }
1857 pw.println(pidString);
1858 }
1859 pw.println();
1860
1861 pw.println("FeatureUsers:");
1862 for (Object requester : mFeatureUsers) {
1863 pw.println(requester.toString());
1864 }
1865 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001866
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001867 synchronized (this) {
1868 pw.println("NetworkTranstionWakeLock is currently " +
1869 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1870 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1871 }
1872 pw.println();
1873
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001874 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001875
1876 if (mInetLog != null) {
1877 pw.println();
1878 pw.println("Inet condition reports:");
1879 for(int i = 0; i < mInetLog.size(); i++) {
1880 pw.println(mInetLog.get(i));
1881 }
1882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
1884
Robert Greenwalt42acef32009-08-12 16:08:25 -07001885 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07001887 public MyHandler(Looper looper) {
1888 super(looper);
1889 }
1890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 @Override
1892 public void handleMessage(Message msg) {
1893 NetworkInfo info;
1894 switch (msg.what) {
1895 case NetworkStateTracker.EVENT_STATE_CHANGED:
1896 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08001897 int type = info.getType();
1898 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08001899
Wink Savilleed9c02b2010-12-03 12:01:38 -08001900 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001901 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08001902 state + "/" + info.getDetailedState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903
1904 // Connectivity state changed:
1905 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001906 // [12-9] Network subtype (for mobile network, as defined
1907 // by TelephonyManager)
1908 // [8-3] Detailed state ordinal (as defined by
1909 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 // [2-0] Network type (as defined by ConnectivityManager)
1911 int eventLogParam = (info.getType() & 0x7) |
1912 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1913 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001914 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001915 eventLogParam);
1916
1917 if (info.getDetailedState() ==
1918 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08001920 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08001922 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001924 // the logic here is, handle SUSPENDED the same as
1925 // DISCONNECTED. The only difference being we are
1926 // broadcasting an intent with NetworkInfo that's
1927 // suspended. This allows the applications an
1928 // opportunity to handle DISCONNECTED and SUSPENDED
1929 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08001931 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 handleConnect(info);
1933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001936 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001937 // TODO: Temporary allowing network configuration
1938 // change not resetting sockets.
1939 // @see bug/4455071
1940 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07001942 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001943 String causedBy = null;
1944 synchronized (ConnectivityService.this) {
1945 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
1946 mNetTransitionWakeLock.isHeld()) {
1947 mNetTransitionWakeLock.release();
1948 causedBy = mNetTransitionWakeLockCausedBy;
1949 }
1950 }
1951 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001952 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001953 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07001954 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001955 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001956 FeatureUser u = (FeatureUser)msg.obj;
1957 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001958 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001959 case EVENT_INET_CONDITION_CHANGE:
1960 {
1961 int netType = msg.arg1;
1962 int condition = msg.arg2;
1963 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001964 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001965 }
1966 case EVENT_INET_CONDITION_HOLD_END:
1967 {
1968 int netType = msg.arg1;
1969 int sequence = msg.arg2;
1970 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001971 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001972 }
1973 case EVENT_SET_NETWORK_PREFERENCE:
1974 {
1975 int preference = msg.arg1;
1976 handleSetNetworkPreference(preference);
1977 break;
1978 }
1979 case EVENT_SET_BACKGROUND_DATA:
1980 {
1981 boolean enabled = (msg.arg1 == ENABLED);
1982 handleSetBackgroundData(enabled);
1983 break;
1984 }
1985 case EVENT_SET_MOBILE_DATA:
1986 {
1987 boolean enabled = (msg.arg1 == ENABLED);
1988 handleSetMobileData(enabled);
1989 break;
1990 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001991 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
1992 {
1993 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001994 break;
1995 }
1996 case EVENT_SET_DEPENDENCY_MET:
1997 {
1998 boolean met = (msg.arg1 == ENABLED);
1999 handleSetDependencyMet(msg.arg2, met);
2000 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 }
2003 }
2004 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002005
2006 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002007 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002008 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002009
2010 if (isTetheringSupported()) {
2011 return mTethering.tether(iface);
2012 } else {
2013 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2014 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002015 }
2016
2017 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002018 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002019 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002020
2021 if (isTetheringSupported()) {
2022 return mTethering.untether(iface);
2023 } else {
2024 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2025 }
2026 }
2027
2028 // javadoc from interface
2029 public int getLastTetherError(String iface) {
2030 enforceTetherAccessPermission();
2031
2032 if (isTetheringSupported()) {
2033 return mTethering.getLastTetherError(iface);
2034 } else {
2035 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2036 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002037 }
2038
2039 // TODO - proper iface API for selection by property, inspection, etc
2040 public String[] getTetherableUsbRegexs() {
2041 enforceTetherAccessPermission();
2042 if (isTetheringSupported()) {
2043 return mTethering.getTetherableUsbRegexs();
2044 } else {
2045 return new String[0];
2046 }
2047 }
2048
2049 public String[] getTetherableWifiRegexs() {
2050 enforceTetherAccessPermission();
2051 if (isTetheringSupported()) {
2052 return mTethering.getTetherableWifiRegexs();
2053 } else {
2054 return new String[0];
2055 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002056 }
2057
Danica Chang6fdd0c62010-08-11 14:54:43 -07002058 public String[] getTetherableBluetoothRegexs() {
2059 enforceTetherAccessPermission();
2060 if (isTetheringSupported()) {
2061 return mTethering.getTetherableBluetoothRegexs();
2062 } else {
2063 return new String[0];
2064 }
2065 }
2066
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002067 // TODO - move iface listing, queries, etc to new module
2068 // javadoc from interface
2069 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002070 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002071 return mTethering.getTetherableIfaces();
2072 }
2073
2074 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002075 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002076 return mTethering.getTetheredIfaces();
2077 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002078
Robert Greenwalt5a735062010-03-02 17:25:02 -08002079 public String[] getTetheringErroredIfaces() {
2080 enforceTetherAccessPermission();
2081 return mTethering.getErroredIfaces();
2082 }
2083
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002084 // if ro.tether.denied = true we default to no tethering
2085 // gservices could set the secure setting to 1 though to enable it on a build where it
2086 // had previously been turned off.
2087 public boolean isTetheringSupported() {
2088 enforceTetherAccessPermission();
2089 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002090 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2091 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2092 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002093 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002094
2095 // An API NetworkStateTrackers can call when they lose their network.
2096 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2097 // whichever happens first. The timer is started by the first caller and not
2098 // restarted by subsequent callers.
2099 public void requestNetworkTransitionWakelock(String forWhom) {
2100 enforceConnectivityInternalPermission();
2101 synchronized (this) {
2102 if (mNetTransitionWakeLock.isHeld()) return;
2103 mNetTransitionWakeLockSerialNumber++;
2104 mNetTransitionWakeLock.acquire();
2105 mNetTransitionWakeLockCausedBy = forWhom;
2106 }
2107 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002108 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002109 mNetTransitionWakeLockSerialNumber, 0),
2110 mNetTransitionWakeLockTimeout);
2111 return;
2112 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002113
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002114 // 100 percent is full good, 0 is full bad.
2115 public void reportInetCondition(int networkType, int percentage) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002116 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002117 mContext.enforceCallingOrSelfPermission(
2118 android.Manifest.permission.STATUS_BAR,
2119 "ConnectivityService");
2120
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002121 if (DBG) {
2122 int pid = getCallingPid();
2123 int uid = getCallingUid();
2124 String s = pid + "(" + uid + ") reports inet is " +
2125 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2126 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2127 mInetLog.add(s);
2128 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2129 mInetLog.remove(0);
2130 }
2131 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002132 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002133 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2134 }
2135
2136 private void handleInetConditionChange(int netType, int condition) {
2137 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002138 log("Inet connectivity change, net=" +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002139 netType + ", condition=" + condition +
2140 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2141 }
2142 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002143 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002144 return;
2145 }
2146 if (mActiveDefaultNetwork != netType) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002147 if (DBG) log("given net not default - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002148 return;
2149 }
2150 mDefaultInetCondition = condition;
2151 int delay;
2152 if (mInetConditionChangeInFlight == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002153 if (DBG) log("starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002154 // setup a new hold to debounce this
2155 if (mDefaultInetCondition > 50) {
2156 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2157 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2158 } else {
2159 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2160 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2161 }
2162 mInetConditionChangeInFlight = true;
2163 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2164 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2165 } else {
2166 // we've set the new condition, when this hold ends that will get
2167 // picked up
Wink Savilleed9c02b2010-12-03 12:01:38 -08002168 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002169 }
2170 }
2171
2172 private void handleInetConditionHoldEnd(int netType, int sequence) {
2173 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002174 log("Inet hold end, net=" + netType +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002175 ", condition =" + mDefaultInetCondition +
2176 ", published condition =" + mDefaultInetConditionPublished);
2177 }
2178 mInetConditionChangeInFlight = false;
2179
2180 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002181 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002182 return;
2183 }
2184 if (mDefaultConnectionSequence != sequence) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002185 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002186 return;
2187 }
2188 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002189 if (DBG) log("no change in condition - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002190 return;
2191 }
2192 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2193 if (networkInfo.isConnected() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002194 if (DBG) log("default network not connected - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002195 return;
2196 }
2197 mDefaultInetConditionPublished = mDefaultInetCondition;
2198 sendInetConditionBroadcast(networkInfo);
2199 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002200 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002201
2202 public synchronized ProxyProperties getProxy() {
2203 if (mGlobalProxy != null) return mGlobalProxy;
2204 if (mDefaultProxy != null) return mDefaultProxy;
2205 return null;
2206 }
2207
2208 public void setGlobalProxy(ProxyProperties proxyProperties) {
2209 enforceChangePermission();
2210 synchronized (mGlobalProxyLock) {
2211 if (proxyProperties == mGlobalProxy) return;
2212 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2213 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2214
2215 String host = "";
2216 int port = 0;
2217 String exclList = "";
2218 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2219 mGlobalProxy = new ProxyProperties(proxyProperties);
2220 host = mGlobalProxy.getHost();
2221 port = mGlobalProxy.getPort();
2222 exclList = mGlobalProxy.getExclusionList();
2223 } else {
2224 mGlobalProxy = null;
2225 }
2226 ContentResolver res = mContext.getContentResolver();
2227 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2228 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002229 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002230 exclList);
2231 }
2232
2233 if (mGlobalProxy == null) {
2234 proxyProperties = mDefaultProxy;
2235 }
2236 sendProxyBroadcast(proxyProperties);
2237 }
2238
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002239 private void loadGlobalProxy() {
2240 ContentResolver res = mContext.getContentResolver();
2241 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2242 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2243 String exclList = Settings.Secure.getString(res,
2244 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2245 if (!TextUtils.isEmpty(host)) {
2246 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2247 synchronized (mGlobalProxyLock) {
2248 mGlobalProxy = proxyProperties;
2249 }
2250 }
2251 }
2252
Robert Greenwalt434203a2010-10-11 16:00:27 -07002253 public ProxyProperties getGlobalProxy() {
2254 synchronized (mGlobalProxyLock) {
2255 return mGlobalProxy;
2256 }
2257 }
2258
2259 private void handleApplyDefaultProxy(int type) {
2260 // check if new default - push it out to all VM if so
2261 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2262 synchronized (this) {
2263 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2264 if (mDefaultProxy == proxy) return;
2265 if (!TextUtils.isEmpty(proxy.getHost())) {
2266 mDefaultProxy = proxy;
2267 } else {
2268 mDefaultProxy = null;
2269 }
2270 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002271 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002272 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2273 if (mGlobalProxy != null) return;
2274 sendProxyBroadcast(proxy);
2275 }
2276
2277 private void handleDeprecatedGlobalHttpProxy() {
2278 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2279 Settings.Secure.HTTP_PROXY);
2280 if (!TextUtils.isEmpty(proxy)) {
2281 String data[] = proxy.split(":");
2282 String proxyHost = data[0];
2283 int proxyPort = 8080;
2284 if (data.length > 1) {
2285 try {
2286 proxyPort = Integer.parseInt(data[1]);
2287 } catch (NumberFormatException e) {
2288 return;
2289 }
2290 }
2291 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2292 setGlobalProxy(p);
2293 }
2294 }
2295
2296 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002297 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002298 log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002299 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002300 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2301 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002302 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002303 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002304 }
2305
2306 private static class SettingsObserver extends ContentObserver {
2307 private int mWhat;
2308 private Handler mHandler;
2309 SettingsObserver(Handler handler, int what) {
2310 super(handler);
2311 mHandler = handler;
2312 mWhat = what;
2313 }
2314
2315 void observe(Context context) {
2316 ContentResolver resolver = context.getContentResolver();
2317 resolver.registerContentObserver(Settings.Secure.getUriFor(
2318 Settings.Secure.HTTP_PROXY), false, this);
2319 }
2320
2321 @Override
2322 public void onChange(boolean selfChange) {
2323 mHandler.obtainMessage(mWhat).sendToTarget();
2324 }
2325 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002326
2327 private void log(String s) {
2328 Slog.d(TAG, s);
2329 }
2330
2331 private void loge(String s) {
2332 Slog.e(TAG, s);
2333 }
Wink Saville9d7d6282011-03-12 14:52:01 -08002334 int convertFeatureToNetworkType(String feature){
2335 int networkType = -1;
2336 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2337 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2338 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2339 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2340 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2341 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2342 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2343 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2344 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2345 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2346 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2347 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2348 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2349 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2350 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2351 }
2352 return networkType;
2353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354}