blob: 60951175d0c6da0bead9a1988df6526a92dc4166 [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
19import android.app.Notification;
20import android.app.NotificationManager;
21import android.content.ContentResolver;
22import android.content.Context;
23import android.content.Intent;
24import android.content.pm.PackageManager;
25import android.net.ConnectivityManager;
26import android.net.IConnectivityManager;
27import android.net.MobileDataStateTracker;
28import android.net.NetworkInfo;
Robert Greenwalt37e65eb2010-08-30 10:56:47 -070029import android.net.LinkProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070031import android.net.NetworkUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.net.wifi.WifiStateTracker;
Irfan Sheriffd649c122010-06-09 15:39:36 -070033import android.net.NetworkUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.os.Binder;
35import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070036import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070037import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.Looper;
39import android.os.Message;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070040import android.os.PowerManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070041import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.ServiceManager;
43import android.os.SystemProperties;
44import android.provider.Settings;
Robert Greenwalt42acef32009-08-12 16:08:25 -070045import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080047import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048
Robert Greenwalt42acef32009-08-12 16:08:25 -070049import com.android.internal.telephony.Phone;
50
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080051import com.android.server.connectivity.Tethering;
52
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -070054import java.io.FileWriter;
55import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.io.PrintWriter;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070057import java.net.InetAddress;
58import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -070059import java.util.ArrayList;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070060import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -070061import java.util.GregorianCalendar;
Robert Greenwalt42acef32009-08-12 16:08:25 -070062import java.util.List;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070063import java.net.InetAddress;
64import java.net.UnknownHostException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065
66/**
67 * @hide
68 */
69public class ConnectivityService extends IConnectivityManager.Stub {
70
Robert Greenwaltba175a52010-10-05 19:12:26 -070071 private static final boolean DBG = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 private static final String TAG = "ConnectivityService";
73
Robert Greenwalt42acef32009-08-12 16:08:25 -070074 // how long to wait before switching back to a radio's default network
75 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
76 // system property that can override the above value
77 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
78 "android.telephony.apn-restore";
79
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080080 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -080081 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 /**
84 * Sometimes we want to refer to the individual network state
85 * trackers separately, and sometimes we just want to treat them
86 * abstractly.
87 */
88 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -070089
90 /**
91 * A per Net list of the PID's that requested access to the net
92 * used both as a refcount and for per-PID DNS selection
93 */
94 private List mNetRequestersPids[];
95
Irfan Sheriffa2a1b912010-06-07 09:03:04 -070096 private WifiWatchdogService mWifiWatchdogService;
97
Robert Greenwalt42acef32009-08-12 16:08:25 -070098 // priority order of the nettrackers
99 // (excluding dynamically set mNetworkPreference)
100 // TODO - move mNetworkTypePreference into this
101 private int[] mPriorityList;
102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103 private Context mContext;
104 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700105 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700106 // 0 is full bad, 100 is full good
107 private int mDefaultInetCondition = 0;
108 private int mDefaultInetConditionPublished = 0;
109 private boolean mInetConditionChangeInFlight = false;
110 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
112 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
114 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700115 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700117 private static final int ENABLED = 1;
118 private static final int DISABLED = 0;
119
120 // Share the event space with NetworkStateTracker (which can't see this
121 // internal class but sends us events). If you change these, change
122 // NetworkStateTracker.java too.
123 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
124 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
125
126 /**
127 * used internally as a delayed event to make us switch back to the
128 * default network
129 */
130 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
131 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
132
133 /**
134 * used internally to change our mobile data enabled flag
135 */
136 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
137 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
138
139 /**
140 * used internally to change our network preference setting
141 * arg1 = networkType to prefer
142 */
143 private static final int EVENT_SET_NETWORK_PREFERENCE =
144 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
145
146 /**
147 * used internally to synchronize inet condition reports
148 * arg1 = networkType
149 * arg2 = condition (0 bad, 100 good)
150 */
151 private static final int EVENT_INET_CONDITION_CHANGE =
152 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
153
154 /**
155 * used internally to mark the end of inet condition hold periods
156 * arg1 = networkType
157 */
158 private static final int EVENT_INET_CONDITION_HOLD_END =
159 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
160
161 /**
162 * used internally to set the background data preference
163 * arg1 = TRUE for enabled, FALSE for disabled
164 */
165 private static final int EVENT_SET_BACKGROUND_DATA =
166 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
167
168 /**
169 * used internally to set enable/disable cellular data
170 * arg1 = ENBALED or DISABLED
171 */
172 private static final int EVENT_SET_MOBILE_DATA =
173 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
174
Robert Greenwaltf3331232010-09-24 14:32:21 -0700175 /**
176 * used internally to clear a wakelock when transitioning
177 * from one net to another
178 */
179 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
180 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
181
Robert Greenwalt42acef32009-08-12 16:08:25 -0700182 private Handler mHandler;
183
184 // list of DeathRecipients used to make sure features are turned off when
185 // a process dies
186 private List mFeatureUsers;
187
Mike Lockwood0f79b542009-08-14 14:18:49 -0400188 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800189 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400190
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700191 private PowerManager.WakeLock mNetTransitionWakeLock;
192 private String mNetTransitionWakeLockCausedBy = "";
193 private int mNetTransitionWakeLockSerialNumber;
194 private int mNetTransitionWakeLockTimeout;
195
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700196 private InetAddress mDefaultDns;
197
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700198 // used in DBG mode to track inet condition reports
199 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
200 private ArrayList mInetLog;
201
Robert Greenwalt511288a2009-12-07 11:33:18 -0800202 private static class NetworkAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700203 /**
204 * Class for holding settings read from resources.
205 */
206 public String mName;
207 public int mType;
208 public int mRadio;
209 public int mPriority;
Robert Greenwalt511288a2009-12-07 11:33:18 -0800210 public NetworkInfo.State mLastState;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700211 public NetworkAttributes(String init) {
212 String fragments[] = init.split(",");
213 mName = fragments[0].toLowerCase();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700214 mType = Integer.parseInt(fragments[1]);
215 mRadio = Integer.parseInt(fragments[2]);
216 mPriority = Integer.parseInt(fragments[3]);
Robert Greenwalt511288a2009-12-07 11:33:18 -0800217 mLastState = NetworkInfo.State.UNKNOWN;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700218 }
219 public boolean isDefault() {
220 return (mType == mRadio);
221 }
222 }
223 NetworkAttributes[] mNetAttributes;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700224 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700225
Robert Greenwalt511288a2009-12-07 11:33:18 -0800226 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700227 public int mSimultaneity;
228 public int mType;
229 public RadioAttributes(String init) {
230 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700231 mType = Integer.parseInt(fragments[0]);
232 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700233 }
234 }
235 RadioAttributes[] mRadioAttributes;
236
Wink Savillebb08caf2010-09-02 19:23:52 -0700237 public static synchronized ConnectivityService getInstance(Context context) {
238 if (sServiceInstance == null) {
239 sServiceInstance = new ConnectivityService(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 }
Wink Savillebb08caf2010-09-02 19:23:52 -0700241 return sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 private ConnectivityService(Context context) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800245 if (DBG) Slog.v(TAG, "ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800246
Wink Savillebb08caf2010-09-02 19:23:52 -0700247 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
248 handlerThread.start();
249 mHandler = new MyHandler(handlerThread.getLooper());
250
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800251 // setup our unique device name
252 String id = Settings.Secure.getString(context.getContentResolver(),
253 Settings.Secure.ANDROID_ID);
254 if (id != null && id.length() > 0) {
255 String name = new String("android_").concat(id);
256 SystemProperties.set("net.hostname", name);
257 }
258
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700259 // read our default dns server ip
260 String dns = Settings.Secure.getString(context.getContentResolver(),
261 Settings.Secure.DEFAULT_DNS_SERVER);
262 if (dns == null || dns.length() == 0) {
263 dns = context.getResources().getString(
264 com.android.internal.R.string.config_default_dns_server);
265 }
266 try {
267 mDefaultDns = InetAddress.getByName(dns);
268 } catch (UnknownHostException e) {
269 Slog.e(TAG, "Error setting defaultDns using " + dns);
270 }
271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 mContext = context;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700273
274 PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
275 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
276 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
277 com.android.internal.R.integer.config_networkTransitionTimeout);
278
Robert Greenwalt42acef32009-08-12 16:08:25 -0700279 mNetTrackers = new NetworkStateTracker[
280 ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700283
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700284 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
285 mNetAttributes = new NetworkAttributes[ConnectivityManager.MAX_NETWORK_TYPE+1];
286
Robert Greenwalt42acef32009-08-12 16:08:25 -0700287 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700288 String[] raStrings = context.getResources().getStringArray(
289 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700290 for (String raString : raStrings) {
291 RadioAttributes r = new RadioAttributes(raString);
292 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800293 Slog.e(TAG, "Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700294 continue;
295 }
296 if (mRadioAttributes[r.mType] != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800297 Slog.e(TAG, "Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700298 r.mType);
299 continue;
300 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700301 mRadioAttributes[r.mType] = r;
302 }
303
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700304 String[] naStrings = context.getResources().getStringArray(
305 com.android.internal.R.array.networkAttributes);
306 for (String naString : naStrings) {
307 try {
308 NetworkAttributes n = new NetworkAttributes(naString);
309 if (n.mType > ConnectivityManager.MAX_NETWORK_TYPE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800310 Slog.e(TAG, "Error in networkAttributes - ignoring attempt to define type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700311 n.mType);
312 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700313 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700314 if (mNetAttributes[n.mType] != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800315 Slog.e(TAG, "Error in networkAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700316 n.mType);
317 continue;
318 }
319 if (mRadioAttributes[n.mRadio] == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800320 Slog.e(TAG, "Error in networkAttributes - ignoring attempt to use undefined " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700321 "radio " + n.mRadio + " in network type " + n.mType);
322 continue;
323 }
324 mNetAttributes[n.mType] = n;
325 mNetworksDefined++;
326 } catch(Exception e) {
327 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700328 }
329 }
330
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700331 // high priority first
332 mPriorityList = new int[mNetworksDefined];
333 {
334 int insertionPoint = mNetworksDefined-1;
335 int currentLowest = 0;
336 int nextLowest = 0;
337 while (insertionPoint > -1) {
338 for (NetworkAttributes na : mNetAttributes) {
339 if (na == null) continue;
340 if (na.mPriority < currentLowest) continue;
341 if (na.mPriority > currentLowest) {
342 if (na.mPriority < nextLowest || nextLowest == 0) {
343 nextLowest = na.mPriority;
344 }
345 continue;
346 }
347 mPriorityList[insertionPoint--] = na.mType;
348 }
349 currentLowest = nextLowest;
350 nextLowest = 0;
351 }
352 }
353
354 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
355 for (int i : mPriorityList) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700356 mNetRequestersPids[i] = new ArrayList();
357 }
358
359 mFeatureUsers = new ArrayList();
360
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700361 mNumDnsEntries = 0;
362
363 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
364 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 /*
366 * Create the network state trackers for Wi-Fi and mobile
367 * data. Maybe this could be done with a factory class,
368 * but it's not clear that it's worth it, given that
369 * the number of different network types is not going
370 * to change very often.
371 */
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800372 boolean noMobileData = !getMobileDataEnabled();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700373 for (int netType : mPriorityList) {
374 switch (mNetAttributes[netType].mRadio) {
375 case ConnectivityManager.TYPE_WIFI:
Joe Onorato8a9b2202010-02-26 18:56:32 -0800376 if (DBG) Slog.v(TAG, "Starting Wifi Service.");
Wink Savillec7a98342010-08-13 16:11:42 -0700377 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700378 WifiService wifiService = new WifiService(context);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700379 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700380 wifiService.checkAndStartWifi();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700381 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Savillec7a98342010-08-13 16:11:42 -0700382 wst.startMonitoring(context, mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700384 //TODO: as part of WWS refactor, create only when needed
Irfan Sheriff0d255342010-07-28 09:35:20 -0700385 mWifiWatchdogService = new WifiWatchdogService(context);
Irfan Sheriffa2a1b912010-06-07 09:03:04 -0700386
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700387 break;
388 case ConnectivityManager.TYPE_MOBILE:
Wink Savillec7a98342010-08-13 16:11:42 -0700389 mNetTrackers[netType] = new MobileDataStateTracker(netType,
390 mNetAttributes[netType].mName);
391 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800392 if (noMobileData) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800393 if (DBG) Slog.d(TAG, "tearing down Mobile networks due to setting");
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800394 mNetTrackers[netType].teardown();
395 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700396 break;
397 default:
Joe Onorato8a9b2202010-02-26 18:56:32 -0800398 Slog.e(TAG, "Trying to create a DataStateTracker for an unknown radio type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700399 mNetAttributes[netType].mRadio);
400 continue;
401 }
402 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800403
Robert Greenwaltdfadaea2010-03-11 15:03:08 -0800404 mTethering = new Tethering(mContext, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800405 mTetheringConfigValid = (((mNetTrackers[ConnectivityManager.TYPE_MOBILE_DUN] != null) ||
406 !mTethering.isDunRequired()) &&
407 (mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700408 mTethering.getTetherableWifiRegexs().length != 0 ||
409 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800410 mTethering.getUpstreamIfaceRegexs().length != 0);
411
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700412 if (DBG) {
413 mInetLog = new ArrayList();
414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 }
416
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700419 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 * @param preference the new preference
421 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700422 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700424
425 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 }
427
428 public int getNetworkPreference() {
429 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700430 int preference;
431 synchronized(this) {
432 preference = mNetworkPreference;
433 }
434 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 }
436
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700437 private void handleSetNetworkPreference(int preference) {
438 if (ConnectivityManager.isNetworkTypeValid(preference) &&
439 mNetAttributes[preference] != null &&
440 mNetAttributes[preference].isDefault()) {
441 if (mNetworkPreference != preference) {
442 final ContentResolver cr = mContext.getContentResolver();
443 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
444 synchronized(this) {
445 mNetworkPreference = preference;
446 }
447 enforcePreference();
448 }
449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 private int getPersistedNetworkPreference() {
453 final ContentResolver cr = mContext.getContentResolver();
454
455 final int networkPrefSetting = Settings.Secure
456 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
457 if (networkPrefSetting != -1) {
458 return networkPrefSetting;
459 }
460
461 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
462 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700465 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 * In this method, we only tear down a non-preferred network. Establishing
467 * a connection to the preferred network is taken care of when we handle
468 * the disconnect event from the non-preferred network
469 * (see {@link #handleDisconnect(NetworkInfo)}).
470 */
471 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700472 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 return;
474
Robert Greenwalt42acef32009-08-12 16:08:25 -0700475 if (!mNetTrackers[mNetworkPreference].isAvailable())
476 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477
Robert Greenwalt42acef32009-08-12 16:08:25 -0700478 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700479 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700480 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700481 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800482 Slog.d(TAG, "tearing down " +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700483 mNetTrackers[t].getNetworkInfo() +
484 " in enforcePreference");
485 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700486 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 }
488 }
489 }
490
491 private boolean teardown(NetworkStateTracker netTracker) {
492 if (netTracker.teardown()) {
493 netTracker.setTeardownRequested(true);
494 return true;
495 } else {
496 return false;
497 }
498 }
499
500 /**
501 * Return NetworkInfo for the active (i.e., connected) network interface.
502 * It is assumed that at most one network is active at a time. If more
503 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700504 * @return the info for the active network, or {@code null} if none is
505 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 */
507 public NetworkInfo getActiveNetworkInfo() {
508 enforceAccessPermission();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700509 for (int type=0; type <= ConnectivityManager.MAX_NETWORK_TYPE; type++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700510 if (mNetAttributes[type] == null || !mNetAttributes[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700511 continue;
512 }
513 NetworkStateTracker t = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 NetworkInfo info = t.getNetworkInfo();
515 if (info.isConnected()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800516 if (DBG && type != mActiveDefaultNetwork) Slog.e(TAG,
Robert Greenwalt42acef32009-08-12 16:08:25 -0700517 "connected default network is not " +
518 "mActiveDefaultNetwork!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 return info;
520 }
521 }
522 return null;
523 }
524
525 public NetworkInfo getNetworkInfo(int networkType) {
526 enforceAccessPermission();
527 if (ConnectivityManager.isNetworkTypeValid(networkType)) {
528 NetworkStateTracker t = mNetTrackers[networkType];
529 if (t != null)
530 return t.getNetworkInfo();
531 }
532 return null;
533 }
534
535 public NetworkInfo[] getAllNetworkInfo() {
536 enforceAccessPermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700537 NetworkInfo[] result = new NetworkInfo[mNetworksDefined];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 int i = 0;
539 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700540 if(t != null) result[i++] = t.getNetworkInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 }
542 return result;
543 }
544
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700545 /**
546 * Return LinkProperties for the active (i.e., connected) default
547 * network interface. It is assumed that at most one default network
548 * is active at a time. If more than one is active, it is indeterminate
549 * which will be returned.
550 * @return the ip properties for the active network, or {@code null} if
551 * none is active
552 */
553 public LinkProperties getActiveLinkProperties() {
554 enforceAccessPermission();
555 for (int type=0; type <= ConnectivityManager.MAX_NETWORK_TYPE; type++) {
556 if (mNetAttributes[type] == null || !mNetAttributes[type].isDefault()) {
557 continue;
558 }
559 NetworkStateTracker t = mNetTrackers[type];
560 NetworkInfo info = t.getNetworkInfo();
561 if (info.isConnected()) {
562 return t.getLinkProperties();
563 }
564 }
565 return null;
566 }
567
568 public LinkProperties getLinkProperties(int networkType) {
569 enforceAccessPermission();
570 if (ConnectivityManager.isNetworkTypeValid(networkType)) {
571 NetworkStateTracker t = mNetTrackers[networkType];
572 if (t != null) return t.getLinkProperties();
573 }
574 return null;
575 }
576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 public boolean setRadios(boolean turnOn) {
578 boolean result = true;
579 enforceChangePermission();
580 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700581 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 }
583 return result;
584 }
585
586 public boolean setRadio(int netType, boolean turnOn) {
587 enforceChangePermission();
588 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
589 return false;
590 }
591 NetworkStateTracker tracker = mNetTrackers[netType];
592 return tracker != null && tracker.setRadio(turnOn);
593 }
594
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700595 /**
596 * Used to notice when the calling process dies so we can self-expire
597 *
598 * Also used to know if the process has cleaned up after itself when
599 * our auto-expire timer goes off. The timer has a link to an object.
600 *
601 */
Robert Greenwalt42acef32009-08-12 16:08:25 -0700602 private class FeatureUser implements IBinder.DeathRecipient {
603 int mNetworkType;
604 String mFeature;
605 IBinder mBinder;
606 int mPid;
607 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -0800608 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700609
610 FeatureUser(int type, String feature, IBinder binder) {
611 super();
612 mNetworkType = type;
613 mFeature = feature;
614 mBinder = binder;
615 mPid = getCallingPid();
616 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -0800617 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700618
Robert Greenwalt42acef32009-08-12 16:08:25 -0700619 try {
620 mBinder.linkToDeath(this, 0);
621 } catch (RemoteException e) {
622 binderDied();
623 }
624 }
625
626 void unlinkDeathRecipient() {
627 mBinder.unlinkToDeath(this, 0);
628 }
629
630 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800631 Slog.d(TAG, "ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800632 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
633 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700634 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700635 }
636
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700637 public void expire() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800638 Slog.d(TAG, "ConnectivityService FeatureUser expire(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800639 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
640 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700641 stopUsingNetworkFeature(this, false);
642 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800643
644 public String toString() {
645 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
646 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
647 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700648 }
649
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700650 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700651 public int startUsingNetworkFeature(int networkType, String feature,
652 IBinder binder) {
653 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800654 Slog.d(TAG, "startUsingNetworkFeature for net " + networkType +
Robert Greenwalt42acef32009-08-12 16:08:25 -0700655 ": " + feature);
656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700658 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
659 mNetAttributes[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700660 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700662
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700663 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700664
665 // TODO - move this into the MobileDataStateTracker
666 int usedNetworkType = networkType;
667 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800668 if (!getMobileDataEnabled()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800669 if (DBG) Slog.d(TAG, "requested special network with data disabled - rejected");
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800670 return Phone.APN_TYPE_NOT_AVAILABLE;
671 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700672 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
673 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
674 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
675 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
676 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN)) {
677 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
678 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
679 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
680 }
681 }
682 NetworkStateTracker network = mNetTrackers[usedNetworkType];
683 if (network != null) {
684 if (usedNetworkType != networkType) {
685 Integer currentPid = new Integer(getCallingPid());
686
687 NetworkStateTracker radio = mNetTrackers[networkType];
688 NetworkInfo ni = network.getNetworkInfo();
689
690 if (ni.isAvailable() == false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800691 if (DBG) Slog.d(TAG, "special network not available");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700692 return Phone.APN_TYPE_NOT_AVAILABLE;
693 }
694
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700695 synchronized(this) {
696 mFeatureUsers.add(f);
697 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
698 // this gets used for per-pid dns when connected
699 mNetRequestersPids[usedNetworkType].add(currentPid);
700 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700701 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700702 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK,
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700703 f), getRestoreDefaultNetworkDelay());
704
Robert Greenwalt42acef32009-08-12 16:08:25 -0700705
Robert Greenwalta64bf832009-08-19 20:19:33 -0700706 if ((ni.isConnectedOrConnecting() == true) &&
707 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700708 if (ni.isConnected() == true) {
709 // add the pid-specific dns
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -0700710 handleDnsConfigurationChange(networkType);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800711 if (DBG) Slog.d(TAG, "special network already active");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700712 return Phone.APN_ALREADY_ACTIVE;
713 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800714 if (DBG) Slog.d(TAG, "special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700715 return Phone.APN_REQUEST_STARTED;
716 }
717
718 // check if the radio in play can make another contact
719 // assume if cannot for now
720
Joe Onorato8a9b2202010-02-26 18:56:32 -0800721 if (DBG) Slog.d(TAG, "reconnecting to special network");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700722 network.reconnect();
723 return Phone.APN_REQUEST_STARTED;
724 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -0700725 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700726 }
727 }
728 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 }
730
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700731 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700733 enforceChangePermission();
734
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700735 int pid = getCallingPid();
736 int uid = getCallingUid();
737
738 FeatureUser u = null;
739 boolean found = false;
740
741 synchronized(this) {
742 for (int i = 0; i < mFeatureUsers.size() ; i++) {
743 u = (FeatureUser)mFeatureUsers.get(i);
744 if (uid == u.mUid && pid == u.mPid &&
745 networkType == u.mNetworkType &&
746 TextUtils.equals(feature, u.mFeature)) {
747 found = true;
748 break;
749 }
750 }
751 }
752 if (found && u != null) {
753 // stop regardless of how many other time this proc had called start
754 return stopUsingNetworkFeature(u, true);
755 } else {
756 // none found!
Joe Onorato8a9b2202010-02-26 18:56:32 -0800757 if (DBG) Slog.d(TAG, "ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700758 return 1;
759 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700760 }
761
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700762 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
763 int networkType = u.mNetworkType;
764 String feature = u.mFeature;
765 int pid = u.mPid;
766 int uid = u.mUid;
767
768 NetworkStateTracker tracker = null;
769 boolean callTeardown = false; // used to carry our decision outside of sync block
770
Robert Greenwalt42acef32009-08-12 16:08:25 -0700771 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800772 Slog.d(TAG, "stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt42acef32009-08-12 16:08:25 -0700773 ": " + feature);
774 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
777 return -1;
778 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700779
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700780 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
781 // sync block
782 synchronized(this) {
783 // check if this process still has an outstanding start request
784 if (!mFeatureUsers.contains(u)) {
Robert Greenwalt78a640a2010-03-10 16:10:43 -0800785 if (DBG) Slog.d(TAG, "ignoring - this process has no outstanding requests");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700786 return 1;
787 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700788 u.unlinkDeathRecipient();
789 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
790 // If we care about duplicate requests, check for that here.
791 //
792 // This is done to support the extension of a request - the app
793 // can request we start the network feature again and renew the
794 // auto-shutoff delay. Normal "stop" calls from the app though
795 // do not pay attention to duplicate requests - in effect the
796 // API does not refcount and a single stop will counter multiple starts.
797 if (ignoreDups == false) {
798 for (int i = 0; i < mFeatureUsers.size() ; i++) {
799 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
800 if (x.mUid == u.mUid && x.mPid == u.mPid &&
801 x.mNetworkType == u.mNetworkType &&
802 TextUtils.equals(x.mFeature, u.mFeature)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800803 if (DBG) Slog.d(TAG, "ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700804 return 1;
805 }
806 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700807 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700808
809 // TODO - move to MobileDataStateTracker
810 int usedNetworkType = networkType;
811 if (networkType == ConnectivityManager.TYPE_MOBILE) {
812 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
813 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
814 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
815 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
816 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN)) {
817 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
818 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
819 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
820 }
821 }
822 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700823 if (tracker == null) {
Robert Greenwalt78a640a2010-03-10 16:10:43 -0800824 if (DBG) Slog.d(TAG, "ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700825 return -1;
826 }
827 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700828 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700829 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -0800830 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700831 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800832 if (DBG) Slog.d(TAG, "not tearing down special network - " +
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700833 "others still using it");
834 return 1;
835 }
836 callTeardown = true;
837 }
838 }
Robert Greenwalt78a640a2010-03-10 16:10:43 -0800839 if (DBG) Slog.d(TAG, "Doing network teardown");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700840 if (callTeardown) {
841 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700842 return 1;
843 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -0700844 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 }
847
848 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700849 * @deprecated use requestRouteToHostAddress instead
850 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 * Ensure that a network route exists to deliver traffic to the specified
852 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700853 * @param networkType the type of the network over which traffic to the
854 * specified host is to be routed
855 * @param hostAddress the IP address of the host to which the route is
856 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 * @return {@code true} on success, {@code false} on failure
858 */
859 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700860 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
861
862 if (inetAddress == null) {
863 return false;
864 }
865
866 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
867 }
868
869 /**
870 * Ensure that a network route exists to deliver traffic to the specified
871 * host via the specified network interface.
872 * @param networkType the type of the network over which traffic to the
873 * specified host is to be routed
874 * @param hostAddress the IP address of the host to which the route is
875 * desired
876 * @return {@code true} on success, {@code false} on failure
877 */
878 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 enforceChangePermission();
880 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
881 return false;
882 }
883 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -0700884
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700885 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
886 tracker.isTeardownRequested()) {
Robert Greenwalt8206ff32009-09-10 15:06:20 -0700887 if (DBG) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700888 Slog.d(TAG, "requestRouteToHostAddress on down network " +
889 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -0700890 }
891 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700893 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700894 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700895 return addHostRoute(tracker, addr);
896 } catch (UnknownHostException e) {}
897 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700898 }
899
900 /**
901 * Ensure that a network route exists to deliver traffic to the specified
902 * host via the mobile data network.
903 * @param hostAddress the IP address of the host to which the route is desired,
904 * in network byte order.
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700905 * TODO - deprecate
Irfan Sheriffd649c122010-06-09 15:39:36 -0700906 * @return {@code true} on success, {@code false} on failure
907 */
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700908 private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress) {
Irfan Sheriffd649c122010-06-09 15:39:36 -0700909 if (nt.getNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI) {
910 return false;
911 }
912
Robert Greenwalt37e65eb2010-08-30 10:56:47 -0700913 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700914 if (p == null) return false;
915 String interfaceName = p.getInterfaceName();
Irfan Sheriffd649c122010-06-09 15:39:36 -0700916
917 if (DBG) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700918 Slog.d(TAG, "Requested host route to " + hostAddress + "(" + interfaceName + ")");
Irfan Sheriffd649c122010-06-09 15:39:36 -0700919 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700920 if (interfaceName != null) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700921 return NetworkUtils.addHostRoute(interfaceName, hostAddress, null);
Irfan Sheriffd649c122010-06-09 15:39:36 -0700922 } else {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700923 if (DBG) Slog.e(TAG, "addHostRoute failed due to null interface name");
Irfan Sheriffd649c122010-06-09 15:39:36 -0700924 return false;
925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 }
927
928 /**
929 * @see ConnectivityManager#getBackgroundDataSetting()
930 */
931 public boolean getBackgroundDataSetting() {
932 return Settings.Secure.getInt(mContext.getContentResolver(),
933 Settings.Secure.BACKGROUND_DATA, 1) == 1;
934 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 /**
937 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
938 */
939 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
940 mContext.enforceCallingOrSelfPermission(
941 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
942 "ConnectivityService");
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700943
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700944 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
945 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700948 private void handleSetBackgroundData(boolean enabled) {
949 if (enabled != getBackgroundDataSetting()) {
950 Settings.Secure.putInt(mContext.getContentResolver(),
951 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
952 Intent broadcast = new Intent(
953 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
954 mContext.sendBroadcast(broadcast);
955 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700956 }
957
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800958 /**
959 * @see ConnectivityManager#getMobileDataEnabled()
960 */
961 public boolean getMobileDataEnabled() {
962 enforceAccessPermission();
963 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
964 Settings.Secure.MOBILE_DATA, 1) == 1;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800965 if (DBG) Slog.d(TAG, "getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800966 return retVal;
967 }
968
969 /**
970 * @see ConnectivityManager#setMobileDataEnabled(boolean)
971 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700972 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800973 enforceChangePermission();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800974 if (DBG) Slog.d(TAG, "setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800975
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700976 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
977 (enabled ? ENABLED : DISABLED), 0));
978 }
979
980 private void handleSetMobileData(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800981 if (getMobileDataEnabled() == enabled) return;
982
983 Settings.Secure.putInt(mContext.getContentResolver(),
984 Settings.Secure.MOBILE_DATA, enabled ? 1 : 0);
985
986 if (enabled) {
987 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700988 if (DBG) {
989 Slog.d(TAG, "starting up " + mNetTrackers[ConnectivityManager.TYPE_MOBILE]);
990 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800991 mNetTrackers[ConnectivityManager.TYPE_MOBILE].reconnect();
992 }
993 } else {
994 for (NetworkStateTracker nt : mNetTrackers) {
995 if (nt == null) continue;
996 int netType = nt.getNetworkInfo().getType();
997 if (mNetAttributes[netType].mRadio == ConnectivityManager.TYPE_MOBILE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800998 if (DBG) Slog.d(TAG, "tearing down " + nt);
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800999 nt.teardown();
1000 }
1001 }
1002 }
1003 }
1004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 private int getNumConnectedNetworks() {
1006 int numConnectedNets = 0;
1007
1008 for (NetworkStateTracker nt : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001009 if (nt != null && nt.getNetworkInfo().isConnected() &&
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001010 !nt.isTeardownRequested()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 ++numConnectedNets;
1012 }
1013 }
1014 return numConnectedNets;
1015 }
1016
1017 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001018 mContext.enforceCallingOrSelfPermission(
1019 android.Manifest.permission.ACCESS_NETWORK_STATE,
1020 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 }
1022
1023 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001024 mContext.enforceCallingOrSelfPermission(
1025 android.Manifest.permission.CHANGE_NETWORK_STATE,
1026 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 }
1028
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001029 // TODO Make this a special check when it goes public
1030 private void enforceTetherChangePermission() {
1031 mContext.enforceCallingOrSelfPermission(
1032 android.Manifest.permission.CHANGE_NETWORK_STATE,
1033 "ConnectivityService");
1034 }
1035
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001036 private void enforceTetherAccessPermission() {
1037 mContext.enforceCallingOrSelfPermission(
1038 android.Manifest.permission.ACCESS_NETWORK_STATE,
1039 "ConnectivityService");
1040 }
1041
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001042 private void enforceConnectivityInternalPermission() {
1043 mContext.enforceCallingOrSelfPermission(
1044 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1045 "ConnectivityService");
1046 }
1047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001049 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1050 * network, we ignore it. If it is for the active network, we send out a
1051 * broadcast. But first, we check whether it might be possible to connect
1052 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 * @param info the {@code NetworkInfo} for the network
1054 */
1055 private void handleDisconnect(NetworkInfo info) {
1056
Robert Greenwalt42acef32009-08-12 16:08:25 -07001057 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058
Robert Greenwalt42acef32009-08-12 16:08:25 -07001059 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 /*
1061 * If the disconnected network is not the active one, then don't report
1062 * this as a loss of connectivity. What probably happened is that we're
1063 * getting the disconnect for a network that we explicitly disabled
1064 * in accordance with network preference policies.
1065 */
Robert Greenwalt42acef32009-08-12 16:08:25 -07001066 if (!mNetAttributes[prevNetType].isDefault()) {
1067 List pids = mNetRequestersPids[prevNetType];
1068 for (int i = 0; i<pids.size(); i++) {
1069 Integer pid = (Integer)pids.get(i);
1070 // will remove them because the net's no longer connected
1071 // need to do this now as only now do we know the pids and
1072 // can properly null things that are no longer referenced.
1073 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
1076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1078 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1079 if (info.isFailover()) {
1080 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1081 info.setFailover(false);
1082 }
1083 if (info.getReason() != null) {
1084 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1085 }
1086 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001087 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1088 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001090
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001091 NetworkStateTracker newNet = null;
1092 if (mNetAttributes[prevNetType].isDefault()) {
1093 newNet = tryFailover(prevNetType);
1094 if (newNet != null) {
1095 NetworkInfo switchTo = newNet.getNetworkInfo();
Robert Greenwalt029be812010-09-20 18:01:43 -07001096 if (!switchTo.isConnected()) {
1097 // if the other net is connected they've already reset this and perhaps even gotten
1098 // a positive report we don't want to overwrite, but if not we need to clear this now
1099 // to turn our cellular sig strength white
1100 mDefaultInetConditionPublished = 0;
1101 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001102 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1103 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001104 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001105 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1106 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001107 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001108 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001109 // do this before we broadcast the change
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001110 handleConnectivityChange(prevNetType);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001111
1112 sendStickyBroadcast(intent);
1113 /*
1114 * If the failover network is already connected, then immediately send
1115 * out a followup broadcast indicating successful failover
1116 */
1117 if (newNet != null && newNet.getNetworkInfo().isConnected()) {
1118 sendConnectedBroadcast(newNet.getNetworkInfo());
1119 }
1120 }
1121
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001122 // returns null if no failover available
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001123 private NetworkStateTracker tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001124 /*
1125 * If this is a default network, check if other defaults are available
1126 * or active
1127 */
1128 NetworkStateTracker newNet = null;
1129 if (mNetAttributes[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001130 if (mActiveDefaultNetwork == prevNetType) {
1131 mActiveDefaultNetwork = -1;
1132 }
1133
1134 int newType = -1;
1135 int newPriority = -1;
Robert Greenwalt35429592010-02-25 12:04:29 -08001136 boolean noMobileData = !getMobileDataEnabled();
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001137 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001138 if (checkType == prevNetType) continue;
1139 if (mNetAttributes[checkType] == null) continue;
Robert Greenwalt35429592010-02-25 12:04:29 -08001140 if (mNetAttributes[checkType].mRadio == ConnectivityManager.TYPE_MOBILE &&
1141 noMobileData) {
1142 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001143 Slog.d(TAG, "not failing over to mobile type " + checkType +
Robert Greenwalt35429592010-02-25 12:04:29 -08001144 " because Mobile Data Disabled");
1145 }
1146 continue;
1147 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001148 if (mNetAttributes[checkType].isDefault()) {
1149 /* TODO - if we have multiple nets we could use
1150 * we may want to put more thought into which we choose
1151 */
1152 if (checkType == mNetworkPreference) {
1153 newType = checkType;
1154 break;
1155 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001156 if (mNetAttributes[checkType].mPriority > newPriority) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001157 newType = checkType;
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001158 newPriority = mNetAttributes[newType].mPriority;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 }
1161 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001162
1163 if (newType != -1) {
1164 newNet = mNetTrackers[newType];
1165 /**
1166 * See if the other network is available to fail over to.
1167 * If is not available, we enable it anyway, so that it
1168 * will be able to connect when it does become available,
1169 * but we report a total loss of connectivity rather than
1170 * report that we are attempting to fail over.
1171 */
1172 if (newNet.isAvailable()) {
1173 NetworkInfo switchTo = newNet.getNetworkInfo();
1174 switchTo.setFailover(true);
Robert Greenwalta64bf832009-08-19 20:19:33 -07001175 if (!switchTo.isConnectedOrConnecting() ||
1176 newNet.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001177 newNet.reconnect();
1178 }
1179 if (DBG) {
1180 if (switchTo.isConnected()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001181 Slog.v(TAG, "Switching to already connected " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001182 switchTo.getTypeName());
1183 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001184 Slog.v(TAG, "Attempting to switch to " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001185 switchTo.getTypeName());
1186 }
1187 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001188 } else {
1189 newNet.reconnect();
Robert Greenwaltf0fa39e2010-03-09 14:55:08 -08001190 newNet = null; // not officially avail.. try anyway, but
1191 // report no failover
Robert Greenwalt42acef32009-08-12 16:08:25 -07001192 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001195
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001196 return newNet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 }
1198
1199 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001200 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1201 }
1202
1203 private void sendInetConditionBroadcast(NetworkInfo info) {
1204 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1205 }
1206
1207 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1208 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1210 if (info.isFailover()) {
1211 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1212 info.setFailover(false);
1213 }
1214 if (info.getReason() != null) {
1215 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1216 }
1217 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001218 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1219 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001221 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001222 sendStickyBroadcast(intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 }
1224
1225 /**
1226 * Called when an attempt to fail over to another network has failed.
1227 * @param info the {@link NetworkInfo} for the failed network
1228 */
1229 private void handleConnectionFailure(NetworkInfo info) {
1230 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231
Robert Greenwalt42acef32009-08-12 16:08:25 -07001232 String reason = info.getReason();
1233 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001234
Robert Greenwalt42acef32009-08-12 16:08:25 -07001235 if (DBG) {
1236 String reasonText;
1237 if (reason == null) {
1238 reasonText = ".";
1239 } else {
1240 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001242 Slog.v(TAG, "Attempt to connect to " + info.getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001243 " failed" + reasonText);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001245
1246 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1247 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1248 if (getActiveNetworkInfo() == null) {
1249 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1250 }
1251 if (reason != null) {
1252 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1253 }
1254 if (extraInfo != null) {
1255 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1256 }
1257 if (info.isFailover()) {
1258 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1259 info.setFailover(false);
1260 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001261
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001262 NetworkStateTracker newNet = null;
1263 if (mNetAttributes[info.getType()].isDefault()) {
1264 newNet = tryFailover(info.getType());
1265 if (newNet != null) {
1266 NetworkInfo switchTo = newNet.getNetworkInfo();
Robert Greenwalt029be812010-09-20 18:01:43 -07001267 if (!switchTo.isConnected()) {
1268 // if the other net is connected they've already reset this and perhaps even gotten
1269 // a positive report we don't want to overwrite, but if not we need to clear this now
1270 // to turn our cellular sig strength white
1271 mDefaultInetConditionPublished = 0;
1272 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001273 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1274 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001275 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001276 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1277 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001278 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001279
Robert Greenwalt029be812010-09-20 18:01:43 -07001280 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001281 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001282 /*
1283 * If the failover network is already connected, then immediately send
1284 * out a followup broadcast indicating successful failover
1285 */
1286 if (newNet != null && newNet.getNetworkInfo().isConnected()) {
1287 sendConnectedBroadcast(newNet.getNetworkInfo());
1288 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001289 }
1290
1291 private void sendStickyBroadcast(Intent intent) {
1292 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001293 if (!mSystemReady) {
1294 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001295 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001296 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1297 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001298 }
1299 }
1300
1301 void systemReady() {
1302 synchronized(this) {
1303 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001304 if (mInitialBroadcast != null) {
1305 mContext.sendStickyBroadcast(mInitialBroadcast);
1306 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001307 }
1308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 }
1310
1311 private void handleConnect(NetworkInfo info) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001312 int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313
1314 // snapshot isFailover, because sendConnectedBroadcast() resets it
1315 boolean isFailover = info.isFailover();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001316 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317
Robert Greenwalt42acef32009-08-12 16:08:25 -07001318 // if this is a default net and other default is running
1319 // kill the one not preferred
1320 if (mNetAttributes[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001321 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1322 if ((type != mNetworkPreference &&
1323 mNetAttributes[mActiveDefaultNetwork].mPriority >
1324 mNetAttributes[type].mPriority) ||
1325 mNetworkPreference == mActiveDefaultNetwork) {
1326 // don't accept this one
Joe Onorato8a9b2202010-02-26 18:56:32 -08001327 if (DBG) Slog.v(TAG, "Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001328 "to torn down network " + info.getTypeName());
1329 teardown(thisNet);
1330 return;
1331 } else {
1332 // tear down the other
1333 NetworkStateTracker otherNet =
1334 mNetTrackers[mActiveDefaultNetwork];
Joe Onorato8a9b2202010-02-26 18:56:32 -08001335 if (DBG) Slog.v(TAG, "Policy requires " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001336 otherNet.getNetworkInfo().getTypeName() +
1337 " teardown");
1338 if (!teardown(otherNet)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001339 Slog.e(TAG, "Network declined teardown request");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001340 return;
1341 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001342 }
1343 }
1344 synchronized (ConnectivityService.this) {
1345 // have a new default network, release the transition wakelock in a second
1346 // if it's held. The second pause is to allow apps to reconnect over the
1347 // new network
1348 if (mNetTransitionWakeLock.isHeld()) {
1349 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001350 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001351 mNetTransitionWakeLockSerialNumber, 0),
1352 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001353 }
1354 }
1355 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001356 // this will cause us to come up initially as unconnected and switching
1357 // to connected after our normal pause unless somebody reports us as reall
1358 // disconnected
1359 mDefaultInetConditionPublished = 0;
1360 mDefaultConnectionSequence++;
1361 mInetConditionChangeInFlight = false;
1362 // Don't do this - if we never sign in stay, grey
1363 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001366 updateNetworkSettings(thisNet);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001367 handleConnectivityChange(type);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001368 sendConnectedBroadcast(info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 }
1370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001372 * After a change in the connectivity state of a network. We're mainly
1373 * concerned with making sure that the list of DNS servers is set up
1374 * according to which networks are connected, and ensuring that the
1375 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001377 private void handleConnectivityChange(int netType) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001379 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001380 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001382 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001383
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001384 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
1385 if (mNetAttributes[netType].isDefault()) {
1386 addDefaultRoute(mNetTrackers[netType]);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001387 } else {
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001388 addPrivateDnsRoutes(mNetTrackers[netType]);
1389 }
1390 } else {
1391 if (mNetAttributes[netType].isDefault()) {
1392 removeDefaultRoute(mNetTrackers[netType]);
1393 } else {
1394 removePrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 }
1397 }
1398
Irfan Sheriffd649c122010-06-09 15:39:36 -07001399 private void addPrivateDnsRoutes(NetworkStateTracker nt) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07001400 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001401 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001402 if (p == null) return;
1403 String interfaceName = p.getInterfaceName();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001404
1405 if (DBG) {
1406 Slog.d(TAG, "addPrivateDnsRoutes for " + nt +
1407 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1408 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001409 if (interfaceName != null && !privateDnsRouteSet) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001410 Collection<InetAddress> dnsList = p.getDnses();
1411 for (InetAddress dns : dnsList) {
1412 if (DBG) Slog.d(TAG, " adding " + dns);
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001413 NetworkUtils.addHostRoute(interfaceName, dns, null);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001414 }
1415 nt.privateDnsRouteSet(true);
1416 }
1417 }
1418
1419 private void removePrivateDnsRoutes(NetworkStateTracker nt) {
1420 // TODO - we should do this explicitly but the NetUtils api doesnt
1421 // support this yet - must remove all. No worse than before
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001422 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001423 if (p == null) return;
1424 String interfaceName = p.getInterfaceName();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001425 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1426 if (interfaceName != null && privateDnsRouteSet) {
1427 if (DBG) {
1428 Slog.d(TAG, "removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
1429 " (" + interfaceName + ")");
1430 }
1431 NetworkUtils.removeHostRoutes(interfaceName);
1432 nt.privateDnsRouteSet(false);
1433 }
1434 }
1435
Irfan Sheriffd649c122010-06-09 15:39:36 -07001436
1437 private void addDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001438 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001439 if (p == null) return;
1440 String interfaceName = p.getInterfaceName();
1441 InetAddress defaultGatewayAddr = p.getGateway();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001442
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001443 if ((interfaceName != null) && (defaultGatewayAddr != null )) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001444 if (!NetworkUtils.addDefaultRoute(interfaceName, defaultGatewayAddr) && DBG) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001445 NetworkInfo networkInfo = nt.getNetworkInfo();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001446 Slog.d(TAG, "addDefaultRoute for " + networkInfo.getTypeName() +
1447 " (" + interfaceName + "), GatewayAddr=" + defaultGatewayAddr);
1448 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001449 }
1450 }
1451
1452
1453 public void removeDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001454 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001455 if (p == null) return;
1456 String interfaceName = p.getInterfaceName();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001457
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001458 if (interfaceName != null) {
1459 if ((NetworkUtils.removeDefaultRoute(interfaceName) >= 0) && DBG) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001460 NetworkInfo networkInfo = nt.getNetworkInfo();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001461 Slog.d(TAG, "removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1462 interfaceName + ")");
1463 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001464 }
1465 }
1466
1467 /**
1468 * Reads the network specific TCP buffer sizes from SystemProperties
1469 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1470 * wide use
1471 */
1472 public void updateNetworkSettings(NetworkStateTracker nt) {
1473 String key = nt.getTcpBufferSizesPropName();
1474 String bufferSizes = SystemProperties.get(key);
1475
1476 if (bufferSizes.length() == 0) {
1477 Slog.e(TAG, key + " not found in system properties. Using defaults");
1478
1479 // Setting to default values so we won't be stuck to previous values
1480 key = "net.tcp.buffersize.default";
1481 bufferSizes = SystemProperties.get(key);
1482 }
1483
1484 // Set values in kernel
1485 if (bufferSizes.length() != 0) {
1486 if (DBG) {
1487 Slog.v(TAG, "Setting TCP values: [" + bufferSizes
1488 + "] which comes from [" + key + "]");
1489 }
1490 setBufferSize(bufferSizes);
1491 }
1492 }
1493
1494 /**
1495 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1496 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1497 *
1498 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1499 * writeMin, writeInitial, writeMax"
1500 */
1501 private void setBufferSize(String bufferSizes) {
1502 try {
1503 String[] values = bufferSizes.split(",");
1504
1505 if (values.length == 6) {
1506 final String prefix = "/sys/kernel/ipv4/tcp_";
1507 stringToFile(prefix + "rmem_min", values[0]);
1508 stringToFile(prefix + "rmem_def", values[1]);
1509 stringToFile(prefix + "rmem_max", values[2]);
1510 stringToFile(prefix + "wmem_min", values[3]);
1511 stringToFile(prefix + "wmem_def", values[4]);
1512 stringToFile(prefix + "wmem_max", values[5]);
1513 } else {
1514 Slog.e(TAG, "Invalid buffersize string: " + bufferSizes);
1515 }
1516 } catch (IOException e) {
1517 Slog.e(TAG, "Can't set tcp buffer sizes:" + e);
1518 }
1519 }
1520
1521 /**
1522 * Writes string to file. Basically same as "echo -n $string > $filename"
1523 *
1524 * @param filename
1525 * @param string
1526 * @throws IOException
1527 */
1528 private void stringToFile(String filename, String string) throws IOException {
1529 FileWriter out = new FileWriter(filename);
1530 try {
1531 out.write(string);
1532 } finally {
1533 out.close();
1534 }
1535 }
1536
1537
Robert Greenwalt42acef32009-08-12 16:08:25 -07001538 /**
1539 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1540 * on the highest priority active net which this process requested.
1541 * If there aren't any, clear it out
1542 */
1543 private void reassessPidDns(int myPid, boolean doBump)
1544 {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001545 if (DBG) Slog.d(TAG, "reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001546 for(int i : mPriorityList) {
1547 if (mNetAttributes[i].isDefault()) {
1548 continue;
1549 }
1550 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001551 if (nt.getNetworkInfo().isConnected() &&
1552 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001553 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001554 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001555 List pids = mNetRequestersPids[i];
1556 for (int j=0; j<pids.size(); j++) {
1557 Integer pid = (Integer)pids.get(j);
1558 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001559 Collection<InetAddress> dnses = p.getDnses();
1560 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001561 if (doBump) {
1562 bumpDns();
1563 }
1564 return;
1565 }
1566 }
1567 }
1568 }
1569 // nothing found - delete
1570 for (int i = 1; ; i++) {
1571 String prop = "net.dns" + i + "." + myPid;
1572 if (SystemProperties.get(prop).length() == 0) {
1573 if (doBump) {
1574 bumpDns();
1575 }
1576 return;
1577 }
1578 SystemProperties.set(prop, "");
1579 }
1580 }
1581
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001582 private void writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001583 int j = 1;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001584 for (InetAddress dns : dnses) {
1585 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001586 }
1587 }
1588
1589 private void bumpDns() {
1590 /*
1591 * Bump the property that tells the name resolver library to reread
1592 * the DNS server list from the properties.
1593 */
1594 String propVal = SystemProperties.get("net.dnschange");
1595 int n = 0;
1596 if (propVal.length() != 0) {
1597 try {
1598 n = Integer.parseInt(propVal);
1599 } catch (NumberFormatException e) {}
1600 }
1601 SystemProperties.set("net.dnschange", "" + (n+1));
1602 }
1603
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001604 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001605 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001606 NetworkStateTracker nt = mNetTrackers[netType];
1607 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001608 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001609 if (p == null) return;
1610 Collection<InetAddress> dnses = p.getDnses();
1611 if (mNetAttributes[netType].isDefault()) {
1612 int j = 1;
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001613 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001614 if (DBG) {
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001615 Slog.d(TAG, "no dns provided - using " + mDefaultDns.getHostAddress());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001616 }
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001617 SystemProperties.set("net.dns1", mDefaultDns.getHostAddress());
1618 j++;
1619 } else {
1620 for (InetAddress dns : dnses) {
1621 if (DBG) {
1622 Slog.d(TAG, "adding dns " + dns + " for " +
1623 nt.getNetworkInfo().getTypeName());
1624 }
1625 SystemProperties.set("net.dns" + j++, dns.getHostAddress());
1626 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001627 }
1628 for (int k=j ; k<mNumDnsEntries; k++) {
1629 if (DBG) Slog.d(TAG, "erasing net.dns" + k);
1630 SystemProperties.set("net.dns" + k, "");
1631 }
1632 mNumDnsEntries = j;
1633 } else {
1634 // set per-pid dns for attached secondary nets
1635 List pids = mNetRequestersPids[netType];
1636 for (int y=0; y< pids.size(); y++) {
1637 Integer pid = (Integer)pids.get(y);
1638 writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 }
1640 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001641 bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001643 }
1644
1645 private int getRestoreDefaultNetworkDelay() {
1646 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1647 NETWORK_RESTORE_DELAY_PROP_NAME);
1648 if(restoreDefaultNetworkDelayStr != null &&
1649 restoreDefaultNetworkDelayStr.length() != 0) {
1650 try {
1651 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1652 } catch (NumberFormatException e) {
1653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001655 return RESTORE_DEFAULT_NETWORK_DELAY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 }
1657
1658 @Override
1659 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001660 if (mContext.checkCallingOrSelfPermission(
1661 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001663 pw.println("Permission Denial: can't dump ConnectivityService " +
1664 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1665 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 return;
1667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 pw.println();
1669 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08001670 if (nst != null) {
1671 if (nst.getNetworkInfo().isConnected()) {
1672 pw.println("Active network: " + nst.getNetworkInfo().
1673 getTypeName());
1674 }
1675 pw.println(nst.getNetworkInfo());
1676 pw.println(nst);
1677 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001680
1681 pw.println("Network Requester Pids:");
1682 for (int net : mPriorityList) {
1683 String pidString = net + ": ";
1684 for (Object pid : mNetRequestersPids[net]) {
1685 pidString = pidString + pid.toString() + ", ";
1686 }
1687 pw.println(pidString);
1688 }
1689 pw.println();
1690
1691 pw.println("FeatureUsers:");
1692 for (Object requester : mFeatureUsers) {
1693 pw.println(requester.toString());
1694 }
1695 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001696
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001697 synchronized (this) {
1698 pw.println("NetworkTranstionWakeLock is currently " +
1699 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1700 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1701 }
1702 pw.println();
1703
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001704 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001705
1706 if (mInetLog != null) {
1707 pw.println();
1708 pw.println("Inet condition reports:");
1709 for(int i = 0; i < mInetLog.size(); i++) {
1710 pw.println(mInetLog.get(i));
1711 }
1712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 }
1714
Robert Greenwalt42acef32009-08-12 16:08:25 -07001715 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07001717 public MyHandler(Looper looper) {
1718 super(looper);
1719 }
1720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 @Override
1722 public void handleMessage(Message msg) {
1723 NetworkInfo info;
1724 switch (msg.what) {
1725 case NetworkStateTracker.EVENT_STATE_CHANGED:
1726 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08001727 int type = info.getType();
1728 NetworkInfo.State state = info.getState();
Robert Greenwalt6e6dec22010-01-25 16:14:00 -08001729 // only do this optimization for wifi. It going into scan mode for location
1730 // services generates alot of noise. Meanwhile the mms apn won't send out
1731 // subsequent notifications when on default cellular because it never
1732 // disconnects.. so only do this to wifi notifications. Fixed better when the
1733 // APN notifications are standardized.
1734 if (mNetAttributes[type].mLastState == state &&
1735 mNetAttributes[type].mRadio == ConnectivityManager.TYPE_WIFI) {
Robert Greenwalt511288a2009-12-07 11:33:18 -08001736 if (DBG) {
Robert Greenwalt6e6dec22010-01-25 16:14:00 -08001737 // TODO - remove this after we validate the dropping doesn't break
1738 // anything
Joe Onorato8a9b2202010-02-26 18:56:32 -08001739 Slog.d(TAG, "Dropping ConnectivityChange for " +
Robert Greenwalt1193ae42010-01-13 09:36:31 -08001740 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08001741 state + "/" + info.getDetailedState());
1742 }
1743 return;
1744 }
1745 mNetAttributes[type].mLastState = state;
1746
Joe Onorato8a9b2202010-02-26 18:56:32 -08001747 if (DBG) Slog.d(TAG, "ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001748 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08001749 state + "/" + info.getDetailedState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750
1751 // Connectivity state changed:
1752 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001753 // [12-9] Network subtype (for mobile network, as defined
1754 // by TelephonyManager)
1755 // [8-3] Detailed state ordinal (as defined by
1756 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 // [2-0] Network type (as defined by ConnectivityManager)
1758 int eventLogParam = (info.getType() & 0x7) |
1759 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1760 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001761 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001762 eventLogParam);
1763
1764 if (info.getDetailedState() ==
1765 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08001767 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08001769 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001771 // the logic here is, handle SUSPENDED the same as
1772 // DISCONNECTED. The only difference being we are
1773 // broadcasting an intent with NetworkInfo that's
1774 // suspended. This allows the applications an
1775 // opportunity to handle DISCONNECTED and SUSPENDED
1776 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08001778 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 handleConnect(info);
1780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001783 // TODO - make this handle ip/proxy/gateway/dns changes
1784 info = (NetworkInfo) msg.obj;
1785 type = info.getType();
1786 handleDnsConfigurationChange(type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07001788 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001789 String causedBy = null;
1790 synchronized (ConnectivityService.this) {
1791 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
1792 mNetTransitionWakeLock.isHeld()) {
1793 mNetTransitionWakeLock.release();
1794 causedBy = mNetTransitionWakeLockCausedBy;
1795 }
1796 }
1797 if (causedBy != null) {
1798 Slog.d(TAG, "NetTransition Wakelock for " +
1799 causedBy + " released by timeout");
1800 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07001801 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001802 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001803 FeatureUser u = (FeatureUser)msg.obj;
1804 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001805 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001806 case EVENT_INET_CONDITION_CHANGE:
1807 {
1808 int netType = msg.arg1;
1809 int condition = msg.arg2;
1810 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001811 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001812 }
1813 case EVENT_INET_CONDITION_HOLD_END:
1814 {
1815 int netType = msg.arg1;
1816 int sequence = msg.arg2;
1817 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001818 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001819 }
1820 case EVENT_SET_NETWORK_PREFERENCE:
1821 {
1822 int preference = msg.arg1;
1823 handleSetNetworkPreference(preference);
1824 break;
1825 }
1826 case EVENT_SET_BACKGROUND_DATA:
1827 {
1828 boolean enabled = (msg.arg1 == ENABLED);
1829 handleSetBackgroundData(enabled);
1830 break;
1831 }
1832 case EVENT_SET_MOBILE_DATA:
1833 {
1834 boolean enabled = (msg.arg1 == ENABLED);
1835 handleSetMobileData(enabled);
1836 break;
1837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 }
1839 }
1840 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001841
1842 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08001843 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001844 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08001845
1846 if (isTetheringSupported()) {
1847 return mTethering.tether(iface);
1848 } else {
1849 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1850 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001851 }
1852
1853 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08001854 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001855 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08001856
1857 if (isTetheringSupported()) {
1858 return mTethering.untether(iface);
1859 } else {
1860 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1861 }
1862 }
1863
1864 // javadoc from interface
1865 public int getLastTetherError(String iface) {
1866 enforceTetherAccessPermission();
1867
1868 if (isTetheringSupported()) {
1869 return mTethering.getLastTetherError(iface);
1870 } else {
1871 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1872 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001873 }
1874
1875 // TODO - proper iface API for selection by property, inspection, etc
1876 public String[] getTetherableUsbRegexs() {
1877 enforceTetherAccessPermission();
1878 if (isTetheringSupported()) {
1879 return mTethering.getTetherableUsbRegexs();
1880 } else {
1881 return new String[0];
1882 }
1883 }
1884
1885 public String[] getTetherableWifiRegexs() {
1886 enforceTetherAccessPermission();
1887 if (isTetheringSupported()) {
1888 return mTethering.getTetherableWifiRegexs();
1889 } else {
1890 return new String[0];
1891 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001892 }
1893
Danica Chang6fdd0c62010-08-11 14:54:43 -07001894 public String[] getTetherableBluetoothRegexs() {
1895 enforceTetherAccessPermission();
1896 if (isTetheringSupported()) {
1897 return mTethering.getTetherableBluetoothRegexs();
1898 } else {
1899 return new String[0];
1900 }
1901 }
1902
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001903 // TODO - move iface listing, queries, etc to new module
1904 // javadoc from interface
1905 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001906 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001907 return mTethering.getTetherableIfaces();
1908 }
1909
1910 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001911 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001912 return mTethering.getTetheredIfaces();
1913 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001914
Robert Greenwalt5a735062010-03-02 17:25:02 -08001915 public String[] getTetheringErroredIfaces() {
1916 enforceTetherAccessPermission();
1917 return mTethering.getErroredIfaces();
1918 }
1919
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001920 // if ro.tether.denied = true we default to no tethering
1921 // gservices could set the secure setting to 1 though to enable it on a build where it
1922 // had previously been turned off.
1923 public boolean isTetheringSupported() {
1924 enforceTetherAccessPermission();
1925 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08001926 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
1927 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
1928 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001929 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001930
1931 // An API NetworkStateTrackers can call when they lose their network.
1932 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
1933 // whichever happens first. The timer is started by the first caller and not
1934 // restarted by subsequent callers.
1935 public void requestNetworkTransitionWakelock(String forWhom) {
1936 enforceConnectivityInternalPermission();
1937 synchronized (this) {
1938 if (mNetTransitionWakeLock.isHeld()) return;
1939 mNetTransitionWakeLockSerialNumber++;
1940 mNetTransitionWakeLock.acquire();
1941 mNetTransitionWakeLockCausedBy = forWhom;
1942 }
1943 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001944 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001945 mNetTransitionWakeLockSerialNumber, 0),
1946 mNetTransitionWakeLockTimeout);
1947 return;
1948 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07001949
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001950 // 100 percent is full good, 0 is full bad.
1951 public void reportInetCondition(int networkType, int percentage) {
1952 if (DBG) Slog.d(TAG, "reportNetworkCondition(" + networkType + ", " + percentage + ")");
1953 mContext.enforceCallingOrSelfPermission(
1954 android.Manifest.permission.STATUS_BAR,
1955 "ConnectivityService");
1956
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001957 if (DBG) {
1958 int pid = getCallingPid();
1959 int uid = getCallingUid();
1960 String s = pid + "(" + uid + ") reports inet is " +
1961 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
1962 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
1963 mInetLog.add(s);
1964 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
1965 mInetLog.remove(0);
1966 }
1967 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001968 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001969 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
1970 }
1971
1972 private void handleInetConditionChange(int netType, int condition) {
1973 if (DBG) {
1974 Slog.d(TAG, "Inet connectivity change, net=" +
1975 netType + ", condition=" + condition +
1976 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
1977 }
1978 if (mActiveDefaultNetwork == -1) {
1979 if (DBG) Slog.d(TAG, "no active default network - aborting");
1980 return;
1981 }
1982 if (mActiveDefaultNetwork != netType) {
1983 if (DBG) Slog.d(TAG, "given net not default - aborting");
1984 return;
1985 }
1986 mDefaultInetCondition = condition;
1987 int delay;
1988 if (mInetConditionChangeInFlight == false) {
1989 if (DBG) Slog.d(TAG, "starting a change hold");
1990 // setup a new hold to debounce this
1991 if (mDefaultInetCondition > 50) {
1992 delay = Settings.Secure.getInt(mContext.getContentResolver(),
1993 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
1994 } else {
1995 delay = Settings.Secure.getInt(mContext.getContentResolver(),
1996 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
1997 }
1998 mInetConditionChangeInFlight = true;
1999 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2000 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2001 } else {
2002 // we've set the new condition, when this hold ends that will get
2003 // picked up
2004 if (DBG) Slog.d(TAG, "currently in hold - not setting new end evt");
2005 }
2006 }
2007
2008 private void handleInetConditionHoldEnd(int netType, int sequence) {
2009 if (DBG) {
2010 Slog.d(TAG, "Inet hold end, net=" + netType +
2011 ", condition =" + mDefaultInetCondition +
2012 ", published condition =" + mDefaultInetConditionPublished);
2013 }
2014 mInetConditionChangeInFlight = false;
2015
2016 if (mActiveDefaultNetwork == -1) {
2017 if (DBG) Slog.d(TAG, "no active default network - aborting");
2018 return;
2019 }
2020 if (mDefaultConnectionSequence != sequence) {
2021 if (DBG) Slog.d(TAG, "event hold for obsolete network - aborting");
2022 return;
2023 }
2024 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2025 if (DBG) Slog.d(TAG, "no change in condition - aborting");
2026 return;
2027 }
2028 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2029 if (networkInfo.isConnected() == false) {
2030 if (DBG) Slog.d(TAG, "default network not connected - aborting");
2031 return;
2032 }
2033 mDefaultInetConditionPublished = mDefaultInetCondition;
2034 sendInetConditionBroadcast(networkInfo);
2035 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037}