blob: c18262e1d388e105373fb9080901a17b58cc9861 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
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 Greenwalt1f1bcfe2010-08-30 10:56:47 -070029import android.net.LinkProperties;
The Android Open Source Project28527d22009-03-03 19:31:44 -080030import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070031import android.net.NetworkUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080032import android.net.wifi.WifiStateTracker;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070033import android.net.NetworkUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080034import android.os.Binder;
35import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070036import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070037import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -080038import android.os.Looper;
39import android.os.Message;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070040import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070041import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080042import android.os.ServiceManager;
43import android.os.SystemProperties;
44import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070045import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080046import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080047import android.util.Slog;
The Android Open Source Project28527d22009-03-03 19:31:44 -080048
Robert Greenwalt2034b912009-08-12 16:08:25 -070049import com.android.internal.telephony.Phone;
50
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080051import com.android.server.connectivity.Tethering;
52
The Android Open Source Project28527d22009-03-03 19:31:44 -080053import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070054import java.io.FileWriter;
55import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080056import java.io.PrintWriter;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070057import java.net.InetAddress;
58import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -070059import java.util.ArrayList;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070060import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -070061import java.util.GregorianCalendar;
Robert Greenwalt2034b912009-08-12 16:08:25 -070062import java.util.List;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070063import java.net.InetAddress;
64import java.net.UnknownHostException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065
66/**
67 * @hide
68 */
69public class ConnectivityService extends IConnectivityManager.Stub {
70
Robert Greenwalt063dc7d2010-10-05 19:12:26 -070071 private static final boolean DBG = true;
The Android Open Source Project28527d22009-03-03 19:31:44 -080072 private static final String TAG = "ConnectivityService";
73
Robert Greenwalt2034b912009-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 Greenwalt0c4828c2010-01-26 11:40:34 -080080 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -080081 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080082
The Android Open Source Project28527d22009-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 Greenwalt2034b912009-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 Sheriff653e2a22010-06-07 09:03:04 -070096 private WifiWatchdogService mWifiWatchdogService;
97
Robert Greenwalt2034b912009-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 Project28527d22009-03-03 19:31:44 -0800103 private Context mContext;
104 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700105 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-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 Project28527d22009-03-03 19:31:44 -0800111
112 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800113
114 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700115 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800116
Robert Greenwalt6a2db8a2010-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 Greenwaltccb36f92010-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 Greenwalt2034b912009-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 Lockwoodfde2b762009-08-14 14:18:49 -0400188 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800189 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400190
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700191 private PowerManager.WakeLock mNetTransitionWakeLock;
192 private String mNetTransitionWakeLockCausedBy = "";
193 private int mNetTransitionWakeLockSerialNumber;
194 private int mNetTransitionWakeLockTimeout;
195
Robert Greenwalt94daa182010-09-01 11:34:05 -0700196 private InetAddress mDefaultDns;
197
Robert Greenwalt0e80be12010-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 Greenwalt12c44552009-12-07 11:33:18 -0800202 private static class NetworkAttributes {
Robert Greenwalt2034b912009-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 Greenwalt12c44552009-12-07 11:33:18 -0800210 public NetworkInfo.State mLastState;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700211 public NetworkAttributes(String init) {
212 String fragments[] = init.split(",");
213 mName = fragments[0].toLowerCase();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700214 mType = Integer.parseInt(fragments[1]);
215 mRadio = Integer.parseInt(fragments[2]);
216 mPriority = Integer.parseInt(fragments[3]);
Robert Greenwalt12c44552009-12-07 11:33:18 -0800217 mLastState = NetworkInfo.State.UNKNOWN;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700218 }
219 public boolean isDefault() {
220 return (mType == mRadio);
221 }
222 }
223 NetworkAttributes[] mNetAttributes;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700224 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700225
Robert Greenwalt12c44552009-12-07 11:33:18 -0800226 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700227 public int mSimultaneity;
228 public int mType;
229 public RadioAttributes(String init) {
230 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700231 mType = Integer.parseInt(fragments[0]);
232 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700233 }
234 }
235 RadioAttributes[] mRadioAttributes;
236
Wink Saville775aad62010-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 Project28527d22009-03-03 19:31:44 -0800240 }
Wink Saville775aad62010-09-02 19:23:52 -0700241 return sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800242 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700243
The Android Open Source Project28527d22009-03-03 19:31:44 -0800244 private ConnectivityService(Context context) {
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800245 if (DBG) Slog.v(TAG, "ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800246
Wink Saville775aad62010-09-02 19:23:52 -0700247 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
248 handlerThread.start();
249 mHandler = new MyHandler(handlerThread.getLooper());
250
Robert Greenwaltd48f8ee2010-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 Greenwalt94daa182010-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 Project28527d22009-03-03 19:31:44 -0800272 mContext = context;
Robert Greenwalt93dc1042010-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 Greenwalt2034b912009-08-12 16:08:25 -0700279 mNetTrackers = new NetworkStateTracker[
280 ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700281
The Android Open Source Project28527d22009-03-03 19:31:44 -0800282 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700283
Robert Greenwaltec05b3c2009-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 Greenwalt2034b912009-08-12 16:08:25 -0700287 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700288 String[] raStrings = context.getResources().getStringArray(
289 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-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 Onoratoc2386bb2010-02-26 18:56:32 -0800293 Slog.e(TAG, "Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700294 continue;
295 }
296 if (mRadioAttributes[r.mType] != null) {
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800297 Slog.e(TAG, "Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700298 r.mType);
299 continue;
300 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700301 mRadioAttributes[r.mType] = r;
302 }
303
Robert Greenwaltec05b3c2009-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 Onoratoc2386bb2010-02-26 18:56:32 -0800310 Slog.e(TAG, "Error in networkAttributes - ignoring attempt to define type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700311 n.mType);
312 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700313 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700314 if (mNetAttributes[n.mType] != null) {
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800315 Slog.e(TAG, "Error in networkAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700316 n.mType);
317 continue;
318 }
319 if (mRadioAttributes[n.mRadio] == null) {
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800320 Slog.e(TAG, "Error in networkAttributes - ignoring attempt to use undefined " +
Robert Greenwaltec05b3c2009-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 Greenwalt2034b912009-08-12 16:08:25 -0700328 }
329 }
330
Robert Greenwaltec05b3c2009-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 Greenwalt2034b912009-08-12 16:08:25 -0700356 mNetRequestersPids[i] = new ArrayList();
357 }
358
359 mFeatureUsers = new ArrayList();
360
Robert Greenwaltec05b3c2009-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 Project28527d22009-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 Greenwalt1b21f6c2010-02-23 18:58:05 -0800372 boolean noMobileData = !getMobileDataEnabled();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700373 for (int netType : mPriorityList) {
374 switch (mNetAttributes[netType].mRadio) {
375 case ConnectivityManager.TYPE_WIFI:
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800376 if (DBG) Slog.v(TAG, "Starting Wifi Service.");
Wink Saville7fabfa22010-08-13 16:11:42 -0700377 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff25be0762010-07-28 09:35:20 -0700378 WifiService wifiService = new WifiService(context);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700379 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff25be0762010-07-28 09:35:20 -0700380 wifiService.checkAndStartWifi();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700381 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Saville7fabfa22010-08-13 16:11:42 -0700382 wst.startMonitoring(context, mHandler);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800383
Irfan Sheriff653e2a22010-06-07 09:03:04 -0700384 //TODO: as part of WWS refactor, create only when needed
Irfan Sheriff25be0762010-07-28 09:35:20 -0700385 mWifiWatchdogService = new WifiWatchdogService(context);
Irfan Sheriff653e2a22010-06-07 09:03:04 -0700386
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700387 break;
388 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700389 mNetTrackers[netType] = new MobileDataStateTracker(netType,
390 mNetAttributes[netType].mName);
391 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -0800392 if (noMobileData) {
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800393 if (DBG) Slog.d(TAG, "tearing down Mobile networks due to setting");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -0800394 mNetTrackers[netType].teardown();
395 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700396 break;
397 default:
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800398 Slog.e(TAG, "Trying to create a DataStateTracker for an unknown radio type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700399 mNetAttributes[netType].mRadio);
400 continue;
401 }
402 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800403
Robert Greenwaltc0b6c602010-03-11 15:03:08 -0800404 mTethering = new Tethering(mContext, mHandler.getLooper());
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800405 mTetheringConfigValid = (((mNetTrackers[ConnectivityManager.TYPE_MOBILE_DUN] != null) ||
406 !mTethering.isDunRequired()) &&
407 (mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700408 mTethering.getTetherableWifiRegexs().length != 0 ||
409 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800410 mTethering.getUpstreamIfaceRegexs().length != 0);
411
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700412 if (DBG) {
413 mInetLog = new ArrayList();
414 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800415 }
416
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700417
The Android Open Source Project28527d22009-03-03 19:31:44 -0800418 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700419 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800420 * @param preference the new preference
421 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700422 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800423 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700424
425 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800426 }
427
428 public int getNetworkPreference() {
429 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700430 int preference;
431 synchronized(this) {
432 preference = mNetworkPreference;
433 }
434 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800435 }
436
Robert Greenwalt6a2db8a2010-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 Project28527d22009-03-03 19:31:44 -0800450 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700451
The Android Open Source Project28527d22009-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 Greenwalt0659da32009-07-16 17:21:39 -0700463
The Android Open Source Project28527d22009-03-03 19:31:44 -0800464 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700465 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-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 Greenwalt2034b912009-08-12 16:08:25 -0700472 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800473 return;
474
Robert Greenwalt2034b912009-08-12 16:08:25 -0700475 if (!mNetTrackers[mNetworkPreference].isAvailable())
476 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800477
Robert Greenwalt2034b912009-08-12 16:08:25 -0700478 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700479 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700480 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700481 if (DBG) {
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800482 Slog.d(TAG, "tearing down " +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700483 mNetTrackers[t].getNetworkInfo() +
484 " in enforcePreference");
485 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700486 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-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 Greenwalt0659da32009-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 Project28527d22009-03-03 19:31:44 -0800506 */
507 public NetworkInfo getActiveNetworkInfo() {
508 enforceAccessPermission();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700509 for (int type=0; type <= ConnectivityManager.MAX_NETWORK_TYPE; type++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700510 if (mNetAttributes[type] == null || !mNetAttributes[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700511 continue;
512 }
513 NetworkStateTracker t = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -0800514 NetworkInfo info = t.getNetworkInfo();
515 if (info.isConnected()) {
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800516 if (DBG && type != mActiveDefaultNetwork) Slog.e(TAG,
Robert Greenwalt2034b912009-08-12 16:08:25 -0700517 "connected default network is not " +
518 "mActiveDefaultNetwork!");
The Android Open Source Project28527d22009-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 Greenwaltec05b3c2009-10-30 14:17:42 -0700537 NetworkInfo[] result = new NetworkInfo[mNetworksDefined];
The Android Open Source Project28527d22009-03-03 19:31:44 -0800538 int i = 0;
539 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700540 if(t != null) result[i++] = t.getNetworkInfo();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800541 }
542 return result;
543 }
544
Robert Greenwalt9f0ee4f2010-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 Project28527d22009-03-03 19:31:44 -0800577 public boolean setRadios(boolean turnOn) {
578 boolean result = true;
579 enforceChangePermission();
580 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700581 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-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 Greenwaltaffc3a12009-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 Greenwalt2034b912009-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 Greenwalt3eeb6032009-12-21 18:24:07 -0800608 long mCreateTime;
Robert Greenwalt2034b912009-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 Greenwalt3eeb6032009-12-21 18:24:07 -0800617 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700618
Robert Greenwalt2034b912009-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 Onoratoc2386bb2010-02-26 18:56:32 -0800631 Slog.d(TAG, "ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800632 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
633 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700634 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700635 }
636
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700637 public void expire() {
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800638 Slog.d(TAG, "ConnectivityService FeatureUser expire(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800639 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
640 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700641 stopUsingNetworkFeature(this, false);
642 }
Robert Greenwalt3eeb6032009-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 Greenwalt2034b912009-08-12 16:08:25 -0700648 }
649
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700650 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700651 public int startUsingNetworkFeature(int networkType, String feature,
652 IBinder binder) {
653 if (DBG) {
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800654 Slog.d(TAG, "startUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700655 ": " + feature);
656 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800657 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700658 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
659 mNetAttributes[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700660 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800661 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700662
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700663 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700664
665 // TODO - move this into the MobileDataStateTracker
666 int usedNetworkType = networkType;
667 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -0800668 if (!getMobileDataEnabled()) {
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800669 if (DBG) Slog.d(TAG, "requested special network with data disabled - rejected");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -0800670 return Phone.APN_TYPE_NOT_AVAILABLE;
671 }
Robert Greenwalt2034b912009-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 Onoratoc2386bb2010-02-26 18:56:32 -0800691 if (DBG) Slog.d(TAG, "special network not available");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700692 return Phone.APN_TYPE_NOT_AVAILABLE;
693 }
694
Robert Greenwaltaffc3a12009-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 Greenwalt2034b912009-08-12 16:08:25 -0700701 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700702 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK,
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700703 f), getRestoreDefaultNetworkDelay());
704
Robert Greenwalt2034b912009-08-12 16:08:25 -0700705
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700706 if ((ni.isConnectedOrConnecting() == true) &&
707 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700708 if (ni.isConnected() == true) {
709 // add the pid-specific dns
Robert Greenwalt3afbead2010-07-23 15:46:26 -0700710 handleDnsConfigurationChange(networkType);
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800711 if (DBG) Slog.d(TAG, "special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700712 return Phone.APN_ALREADY_ACTIVE;
713 }
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800714 if (DBG) Slog.d(TAG, "special network already connecting");
Robert Greenwalt2034b912009-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 Onoratoc2386bb2010-02-26 18:56:32 -0800721 if (DBG) Slog.d(TAG, "reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700722 network.reconnect();
723 return Phone.APN_REQUEST_STARTED;
724 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -0700725 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700726 }
727 }
728 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800729 }
730
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700731 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800732 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700733 enforceChangePermission();
734
Robert Greenwaltaffc3a12009-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 Onoratoc2386bb2010-02-26 18:56:32 -0800757 if (DBG) Slog.d(TAG, "ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700758 return 1;
759 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700760 }
761
Robert Greenwaltaffc3a12009-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 Greenwalt2034b912009-08-12 16:08:25 -0700771 if (DBG) {
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800772 Slog.d(TAG, "stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700773 ": " + feature);
774 }
Robert Greenwalt28f43012009-10-06 17:52:40 -0700775
The Android Open Source Project28527d22009-03-03 19:31:44 -0800776 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
777 return -1;
778 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700779
Robert Greenwaltaffc3a12009-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 Greenwalt46ceefa2010-03-10 16:10:43 -0800785 if (DBG) Slog.d(TAG, "ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700786 return 1;
787 }
Robert Greenwaltaffc3a12009-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 Onoratoc2386bb2010-02-26 18:56:32 -0800803 if (DBG) Slog.d(TAG, "ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700804 return 1;
805 }
806 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700807 }
Robert Greenwaltaffc3a12009-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 Greenwaltec05b3c2009-10-30 14:17:42 -0700823 if (tracker == null) {
Robert Greenwalt46ceefa2010-03-10 16:10:43 -0800824 if (DBG) Slog.d(TAG, "ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700825 return -1;
826 }
827 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700828 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700829 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -0800830 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700831 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800832 if (DBG) Slog.d(TAG, "not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700833 "others still using it");
834 return 1;
835 }
836 callTeardown = true;
837 }
838 }
Robert Greenwalt46ceefa2010-03-10 16:10:43 -0800839 if (DBG) Slog.d(TAG, "Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700840 if (callTeardown) {
841 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700842 return 1;
843 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -0700844 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700845 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800846 }
847
848 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700849 * @deprecated use requestRouteToHostAddress instead
850 *
The Android Open Source Project28527d22009-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 Greenwalt0659da32009-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 Project28527d22009-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 Greenwalt7fe44cb2010-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 Project28527d22009-03-03 19:31:44 -0800879 enforceChangePermission();
880 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
881 return false;
882 }
883 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -0700884
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700885 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
886 tracker.isTeardownRequested()) {
Robert Greenwalt4666ed02009-09-10 15:06:20 -0700887 if (DBG) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700888 Slog.d(TAG, "requestRouteToHostAddress on down network " +
889 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -0700890 }
891 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800892 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700893 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700894 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700895 return addHostRoute(tracker, addr);
896 } catch (UnknownHostException e) {}
897 return false;
Irfan Sheriff7f132d92010-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 Greenwalta7dfbd32010-06-15 15:43:39 -0700905 * TODO - deprecate
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700906 * @return {@code true} on success, {@code false} on failure
907 */
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700908 private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700909 if (nt.getNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI) {
910 return false;
911 }
912
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -0700913 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700914 if (p == null) return false;
915 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700916
917 if (DBG) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700918 Slog.d(TAG, "Requested host route to " + hostAddress + "(" + interfaceName + ")");
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700919 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700920 if (interfaceName != null) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700921 return NetworkUtils.addHostRoute(interfaceName, hostAddress, null);
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700922 } else {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700923 if (DBG) Slog.e(TAG, "addHostRoute failed due to null interface name");
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700924 return false;
925 }
The Android Open Source Project28527d22009-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 Greenwalt0659da32009-07-16 17:21:39 -0700935
The Android Open Source Project28527d22009-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 Greenwalt0659da32009-07-16 17:21:39 -0700943
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700944 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
945 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
946 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800947
Robert Greenwalt6a2db8a2010-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 Greenwalt0659da32009-07-16 17:21:39 -0700956 }
957
Robert Greenwalt1b21f6c2010-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 Onoratoc2386bb2010-02-26 18:56:32 -0800965 if (DBG) Slog.d(TAG, "getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -0800966 return retVal;
967 }
968
969 /**
970 * @see ConnectivityManager#setMobileDataEnabled(boolean)
971 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700972 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -0800973 enforceChangePermission();
Joe Onoratoc2386bb2010-02-26 18:56:32 -0800974 if (DBG) Slog.d(TAG, "setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -0800975
Robert Greenwalt6a2db8a2010-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 Greenwalt1b21f6c2010-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 Greenwalt6a2db8a2010-09-23 10:05:56 -0700988 if (DBG) {
989 Slog.d(TAG, "starting up " + mNetTrackers[ConnectivityManager.TYPE_MOBILE]);
990 }
Robert Greenwalt1b21f6c2010-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 Onoratoc2386bb2010-02-26 18:56:32 -0800998 if (DBG) Slog.d(TAG, "tearing down " + nt);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -0800999 nt.teardown();
1000 }
1001 }
1002 }
1003 }
1004
The Android Open Source Project28527d22009-03-03 19:31:44 -08001005 private int getNumConnectedNetworks() {
1006 int numConnectedNets = 0;
1007
1008 for (NetworkStateTracker nt : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001009 if (nt != null && nt.getNetworkInfo().isConnected() &&
Robert Greenwalt0659da32009-07-16 17:21:39 -07001010 !nt.isTeardownRequested()) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001011 ++numConnectedNets;
1012 }
1013 }
1014 return numConnectedNets;
1015 }
1016
1017 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001018 mContext.enforceCallingOrSelfPermission(
1019 android.Manifest.permission.ACCESS_NETWORK_STATE,
1020 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001021 }
1022
1023 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001024 mContext.enforceCallingOrSelfPermission(
1025 android.Manifest.permission.CHANGE_NETWORK_STATE,
1026 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001027 }
1028
Robert Greenwalt0c4828c2010-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 Greenwalt8e87f122010-02-11 18:18:40 -08001036 private void enforceTetherAccessPermission() {
1037 mContext.enforceCallingOrSelfPermission(
1038 android.Manifest.permission.ACCESS_NETWORK_STATE,
1039 "ConnectivityService");
1040 }
1041
Robert Greenwalt93dc1042010-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 Project28527d22009-03-03 19:31:44 -08001048 /**
Robert Greenwalt0659da32009-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 Project28527d22009-03-03 19:31:44 -08001053 * @param info the {@code NetworkInfo} for the network
1054 */
1055 private void handleDisconnect(NetworkInfo info) {
1056
Robert Greenwalt2034b912009-08-12 16:08:25 -07001057 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001058
Robert Greenwalt2034b912009-08-12 16:08:25 -07001059 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-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 Greenwalt2034b912009-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 Project28527d22009-03-03 19:31:44 -08001074 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001075 }
1076
The Android Open Source Project28527d22009-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 Greenwalt0659da32009-07-16 17:21:39 -07001087 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1088 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001089 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001090
Robert Greenwalt3cc68d32010-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 Greenwaltb2a9e492010-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 Greenwalt3cc68d32010-01-25 17:54:29 -08001102 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1103 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001104 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001105 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1106 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001107 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001108 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001109 // do this before we broadcast the change
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001110 handleConnectivityChange(prevNetType);
Robert Greenwaltf55ced92010-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 Greenwalt3cc68d32010-01-25 17:54:29 -08001122 // returns null if no failover available
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001123 private NetworkStateTracker tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-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 Greenwalt2034b912009-08-12 16:08:25 -07001130 if (mActiveDefaultNetwork == prevNetType) {
1131 mActiveDefaultNetwork = -1;
1132 }
1133
1134 int newType = -1;
1135 int newPriority = -1;
Robert Greenwalt72451bf2010-02-25 12:04:29 -08001136 boolean noMobileData = !getMobileDataEnabled();
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001137 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001138 if (checkType == prevNetType) continue;
1139 if (mNetAttributes[checkType] == null) continue;
Robert Greenwalt72451bf2010-02-25 12:04:29 -08001140 if (mNetAttributes[checkType].mRadio == ConnectivityManager.TYPE_MOBILE &&
1141 noMobileData) {
Robert Greenwalte981bc52010-10-08 16:35:52 -07001142 Slog.e(TAG, "not failing over to mobile type " + checkType +
1143 " because Mobile Data Disabled");
Robert Greenwalt72451bf2010-02-25 12:04:29 -08001144 continue;
1145 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001146 if (mNetAttributes[checkType].isDefault()) {
1147 /* TODO - if we have multiple nets we could use
1148 * we may want to put more thought into which we choose
1149 */
1150 if (checkType == mNetworkPreference) {
1151 newType = checkType;
1152 break;
1153 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001154 if (mNetAttributes[checkType].mPriority > newPriority) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001155 newType = checkType;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001156 newPriority = mNetAttributes[newType].mPriority;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001157 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001158 }
1159 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001160
1161 if (newType != -1) {
1162 newNet = mNetTrackers[newType];
1163 /**
1164 * See if the other network is available to fail over to.
1165 * If is not available, we enable it anyway, so that it
1166 * will be able to connect when it does become available,
1167 * but we report a total loss of connectivity rather than
1168 * report that we are attempting to fail over.
1169 */
1170 if (newNet.isAvailable()) {
1171 NetworkInfo switchTo = newNet.getNetworkInfo();
1172 switchTo.setFailover(true);
Robert Greenwalta52c75a2009-08-19 20:19:33 -07001173 if (!switchTo.isConnectedOrConnecting() ||
1174 newNet.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001175 newNet.reconnect();
1176 }
1177 if (DBG) {
1178 if (switchTo.isConnected()) {
Joe Onoratoc2386bb2010-02-26 18:56:32 -08001179 Slog.v(TAG, "Switching to already connected " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001180 switchTo.getTypeName());
1181 } else {
Joe Onoratoc2386bb2010-02-26 18:56:32 -08001182 Slog.v(TAG, "Attempting to switch to " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001183 switchTo.getTypeName());
1184 }
1185 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001186 } else {
1187 newNet.reconnect();
Robert Greenwalt12984322010-03-09 14:55:08 -08001188 newNet = null; // not officially avail.. try anyway, but
1189 // report no failover
Robert Greenwalt2034b912009-08-12 16:08:25 -07001190 }
Robert Greenwalte981bc52010-10-08 16:35:52 -07001191 } else {
1192 Slog.e(TAG, "Network failover failing.");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001193 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001194 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001195
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001196 return newNet;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001197 }
1198
1199 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-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 Project28527d22009-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 Greenwalt0659da32009-07-16 17:21:39 -07001218 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1219 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001220 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001221 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001222 sendStickyBroadcast(intent);
The Android Open Source Project28527d22009-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 Project28527d22009-03-03 19:31:44 -08001231
Robert Greenwalt2034b912009-08-12 16:08:25 -07001232 String reason = info.getReason();
1233 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001234
Robert Greenwalte981bc52010-10-08 16:35:52 -07001235 String reasonText;
1236 if (reason == null) {
1237 reasonText = ".";
1238 } else {
1239 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001240 }
Robert Greenwalte981bc52010-10-08 16:35:52 -07001241 Slog.e(TAG, "Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001242
1243 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1244 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1245 if (getActiveNetworkInfo() == null) {
1246 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1247 }
1248 if (reason != null) {
1249 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1250 }
1251 if (extraInfo != null) {
1252 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1253 }
1254 if (info.isFailover()) {
1255 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1256 info.setFailover(false);
1257 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001258
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001259 NetworkStateTracker newNet = null;
1260 if (mNetAttributes[info.getType()].isDefault()) {
1261 newNet = tryFailover(info.getType());
1262 if (newNet != null) {
1263 NetworkInfo switchTo = newNet.getNetworkInfo();
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001264 if (!switchTo.isConnected()) {
Robert Greenwalte981bc52010-10-08 16:35:52 -07001265 // if the other net is connected they've already reset this and perhaps
1266 // even gotten a positive report we don't want to overwrite, but if not
1267 // we need to clear this now to turn our cellular sig strength white
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001268 mDefaultInetConditionPublished = 0;
1269 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001270 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1271 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001272 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001273 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1274 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001275 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001276
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001277 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001278 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001279 /*
1280 * If the failover network is already connected, then immediately send
1281 * out a followup broadcast indicating successful failover
1282 */
1283 if (newNet != null && newNet.getNetworkInfo().isConnected()) {
1284 sendConnectedBroadcast(newNet.getNetworkInfo());
1285 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001286 }
1287
1288 private void sendStickyBroadcast(Intent intent) {
1289 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001290 if (!mSystemReady) {
1291 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001292 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001293 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1294 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001295 }
1296 }
1297
1298 void systemReady() {
1299 synchronized(this) {
1300 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001301 if (mInitialBroadcast != null) {
1302 mContext.sendStickyBroadcast(mInitialBroadcast);
1303 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001304 }
1305 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001306 }
1307
1308 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001309 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001310
1311 // snapshot isFailover, because sendConnectedBroadcast() resets it
1312 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001313 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001314
Robert Greenwalt2034b912009-08-12 16:08:25 -07001315 // if this is a default net and other default is running
1316 // kill the one not preferred
1317 if (mNetAttributes[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001318 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1319 if ((type != mNetworkPreference &&
1320 mNetAttributes[mActiveDefaultNetwork].mPriority >
1321 mNetAttributes[type].mPriority) ||
1322 mNetworkPreference == mActiveDefaultNetwork) {
1323 // don't accept this one
Joe Onoratoc2386bb2010-02-26 18:56:32 -08001324 if (DBG) Slog.v(TAG, "Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001325 "to torn down network " + info.getTypeName());
1326 teardown(thisNet);
1327 return;
1328 } else {
1329 // tear down the other
1330 NetworkStateTracker otherNet =
1331 mNetTrackers[mActiveDefaultNetwork];
Joe Onoratoc2386bb2010-02-26 18:56:32 -08001332 if (DBG) Slog.v(TAG, "Policy requires " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001333 otherNet.getNetworkInfo().getTypeName() +
1334 " teardown");
1335 if (!teardown(otherNet)) {
Joe Onoratoc2386bb2010-02-26 18:56:32 -08001336 Slog.e(TAG, "Network declined teardown request");
Robert Greenwalt2034b912009-08-12 16:08:25 -07001337 return;
1338 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001339 }
1340 }
1341 synchronized (ConnectivityService.this) {
1342 // have a new default network, release the transition wakelock in a second
1343 // if it's held. The second pause is to allow apps to reconnect over the
1344 // new network
1345 if (mNetTransitionWakeLock.isHeld()) {
1346 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001347 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001348 mNetTransitionWakeLockSerialNumber, 0),
1349 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001350 }
1351 }
1352 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001353 // this will cause us to come up initially as unconnected and switching
1354 // to connected after our normal pause unless somebody reports us as reall
1355 // disconnected
1356 mDefaultInetConditionPublished = 0;
1357 mDefaultConnectionSequence++;
1358 mInetConditionChangeInFlight = false;
1359 // Don't do this - if we never sign in stay, grey
1360 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001361 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001362 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001363 updateNetworkSettings(thisNet);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001364 handleConnectivityChange(type);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001365 sendConnectedBroadcast(info);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001366 }
1367
The Android Open Source Project28527d22009-03-03 19:31:44 -08001368 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001369 * After a change in the connectivity state of a network. We're mainly
1370 * concerned with making sure that the list of DNS servers is set up
1371 * according to which networks are connected, and ensuring that the
1372 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001373 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001374 private void handleConnectivityChange(int netType) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001375 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001376 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001377 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001378 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001379 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001380
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001381 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
1382 if (mNetAttributes[netType].isDefault()) {
1383 addDefaultRoute(mNetTrackers[netType]);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001384 } else {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001385 addPrivateDnsRoutes(mNetTrackers[netType]);
1386 }
1387 } else {
1388 if (mNetAttributes[netType].isDefault()) {
1389 removeDefaultRoute(mNetTrackers[netType]);
1390 } else {
1391 removePrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001392 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001393 }
1394 }
1395
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001396 private void addPrivateDnsRoutes(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001397 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001398 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001399 if (p == null) return;
1400 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001401
1402 if (DBG) {
1403 Slog.d(TAG, "addPrivateDnsRoutes for " + nt +
1404 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1405 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001406 if (interfaceName != null && !privateDnsRouteSet) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001407 Collection<InetAddress> dnsList = p.getDnses();
1408 for (InetAddress dns : dnsList) {
1409 if (DBG) Slog.d(TAG, " adding " + dns);
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001410 NetworkUtils.addHostRoute(interfaceName, dns, null);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001411 }
1412 nt.privateDnsRouteSet(true);
1413 }
1414 }
1415
1416 private void removePrivateDnsRoutes(NetworkStateTracker nt) {
1417 // TODO - we should do this explicitly but the NetUtils api doesnt
1418 // support this yet - must remove all. No worse than before
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001419 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001420 if (p == null) return;
1421 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001422 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1423 if (interfaceName != null && privateDnsRouteSet) {
1424 if (DBG) {
1425 Slog.d(TAG, "removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
1426 " (" + interfaceName + ")");
1427 }
1428 NetworkUtils.removeHostRoutes(interfaceName);
1429 nt.privateDnsRouteSet(false);
1430 }
1431 }
1432
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001433
1434 private void addDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001435 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001436 if (p == null) return;
1437 String interfaceName = p.getInterfaceName();
1438 InetAddress defaultGatewayAddr = p.getGateway();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001439
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001440 if ((interfaceName != null) && (defaultGatewayAddr != null )) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001441 if (!NetworkUtils.addDefaultRoute(interfaceName, defaultGatewayAddr) && DBG) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001442 NetworkInfo networkInfo = nt.getNetworkInfo();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001443 Slog.d(TAG, "addDefaultRoute for " + networkInfo.getTypeName() +
1444 " (" + interfaceName + "), GatewayAddr=" + defaultGatewayAddr);
1445 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001446 }
1447 }
1448
1449
1450 public void removeDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001451 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001452 if (p == null) return;
1453 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001454
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001455 if (interfaceName != null) {
1456 if ((NetworkUtils.removeDefaultRoute(interfaceName) >= 0) && DBG) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001457 NetworkInfo networkInfo = nt.getNetworkInfo();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001458 Slog.d(TAG, "removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1459 interfaceName + ")");
1460 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001461 }
1462 }
1463
1464 /**
1465 * Reads the network specific TCP buffer sizes from SystemProperties
1466 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1467 * wide use
1468 */
1469 public void updateNetworkSettings(NetworkStateTracker nt) {
1470 String key = nt.getTcpBufferSizesPropName();
1471 String bufferSizes = SystemProperties.get(key);
1472
1473 if (bufferSizes.length() == 0) {
1474 Slog.e(TAG, key + " not found in system properties. Using defaults");
1475
1476 // Setting to default values so we won't be stuck to previous values
1477 key = "net.tcp.buffersize.default";
1478 bufferSizes = SystemProperties.get(key);
1479 }
1480
1481 // Set values in kernel
1482 if (bufferSizes.length() != 0) {
1483 if (DBG) {
1484 Slog.v(TAG, "Setting TCP values: [" + bufferSizes
1485 + "] which comes from [" + key + "]");
1486 }
1487 setBufferSize(bufferSizes);
1488 }
1489 }
1490
1491 /**
1492 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1493 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1494 *
1495 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1496 * writeMin, writeInitial, writeMax"
1497 */
1498 private void setBufferSize(String bufferSizes) {
1499 try {
1500 String[] values = bufferSizes.split(",");
1501
1502 if (values.length == 6) {
1503 final String prefix = "/sys/kernel/ipv4/tcp_";
1504 stringToFile(prefix + "rmem_min", values[0]);
1505 stringToFile(prefix + "rmem_def", values[1]);
1506 stringToFile(prefix + "rmem_max", values[2]);
1507 stringToFile(prefix + "wmem_min", values[3]);
1508 stringToFile(prefix + "wmem_def", values[4]);
1509 stringToFile(prefix + "wmem_max", values[5]);
1510 } else {
1511 Slog.e(TAG, "Invalid buffersize string: " + bufferSizes);
1512 }
1513 } catch (IOException e) {
1514 Slog.e(TAG, "Can't set tcp buffer sizes:" + e);
1515 }
1516 }
1517
1518 /**
1519 * Writes string to file. Basically same as "echo -n $string > $filename"
1520 *
1521 * @param filename
1522 * @param string
1523 * @throws IOException
1524 */
1525 private void stringToFile(String filename, String string) throws IOException {
1526 FileWriter out = new FileWriter(filename);
1527 try {
1528 out.write(string);
1529 } finally {
1530 out.close();
1531 }
1532 }
1533
1534
Robert Greenwalt2034b912009-08-12 16:08:25 -07001535 /**
1536 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1537 * on the highest priority active net which this process requested.
1538 * If there aren't any, clear it out
1539 */
1540 private void reassessPidDns(int myPid, boolean doBump)
1541 {
Joe Onoratoc2386bb2010-02-26 18:56:32 -08001542 if (DBG) Slog.d(TAG, "reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001543 for(int i : mPriorityList) {
1544 if (mNetAttributes[i].isDefault()) {
1545 continue;
1546 }
1547 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001548 if (nt.getNetworkInfo().isConnected() &&
1549 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001550 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001551 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001552 List pids = mNetRequestersPids[i];
1553 for (int j=0; j<pids.size(); j++) {
1554 Integer pid = (Integer)pids.get(j);
1555 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001556 Collection<InetAddress> dnses = p.getDnses();
1557 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001558 if (doBump) {
1559 bumpDns();
1560 }
1561 return;
1562 }
1563 }
1564 }
1565 }
1566 // nothing found - delete
1567 for (int i = 1; ; i++) {
1568 String prop = "net.dns" + i + "." + myPid;
1569 if (SystemProperties.get(prop).length() == 0) {
1570 if (doBump) {
1571 bumpDns();
1572 }
1573 return;
1574 }
1575 SystemProperties.set(prop, "");
1576 }
1577 }
1578
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001579 private void writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001580 int j = 1;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001581 for (InetAddress dns : dnses) {
1582 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001583 }
1584 }
1585
1586 private void bumpDns() {
1587 /*
1588 * Bump the property that tells the name resolver library to reread
1589 * the DNS server list from the properties.
1590 */
1591 String propVal = SystemProperties.get("net.dnschange");
1592 int n = 0;
1593 if (propVal.length() != 0) {
1594 try {
1595 n = Integer.parseInt(propVal);
1596 } catch (NumberFormatException e) {}
1597 }
1598 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001599 /*
1600 * Tell the VMs to toss their DNS caches
1601 */
1602 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1603 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1604 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001605 }
1606
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001607 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001608 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001609 NetworkStateTracker nt = mNetTrackers[netType];
1610 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001611 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001612 if (p == null) return;
1613 Collection<InetAddress> dnses = p.getDnses();
1614 if (mNetAttributes[netType].isDefault()) {
1615 int j = 1;
Robert Greenwalt94daa182010-09-01 11:34:05 -07001616 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001617 if (DBG) {
Robert Greenwalt94daa182010-09-01 11:34:05 -07001618 Slog.d(TAG, "no dns provided - using " + mDefaultDns.getHostAddress());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001619 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001620 SystemProperties.set("net.dns1", mDefaultDns.getHostAddress());
1621 j++;
1622 } else {
1623 for (InetAddress dns : dnses) {
1624 if (DBG) {
1625 Slog.d(TAG, "adding dns " + dns + " for " +
1626 nt.getNetworkInfo().getTypeName());
1627 }
1628 SystemProperties.set("net.dns" + j++, dns.getHostAddress());
1629 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001630 }
1631 for (int k=j ; k<mNumDnsEntries; k++) {
1632 if (DBG) Slog.d(TAG, "erasing net.dns" + k);
1633 SystemProperties.set("net.dns" + k, "");
1634 }
1635 mNumDnsEntries = j;
1636 } else {
1637 // set per-pid dns for attached secondary nets
1638 List pids = mNetRequestersPids[netType];
1639 for (int y=0; y< pids.size(); y++) {
1640 Integer pid = (Integer)pids.get(y);
1641 writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001642 }
1643 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001644 bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001645 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001646 }
1647
1648 private int getRestoreDefaultNetworkDelay() {
1649 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1650 NETWORK_RESTORE_DELAY_PROP_NAME);
1651 if(restoreDefaultNetworkDelayStr != null &&
1652 restoreDefaultNetworkDelayStr.length() != 0) {
1653 try {
1654 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1655 } catch (NumberFormatException e) {
1656 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001657 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001658 return RESTORE_DEFAULT_NETWORK_DELAY;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001659 }
1660
1661 @Override
1662 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001663 if (mContext.checkCallingOrSelfPermission(
1664 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001665 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001666 pw.println("Permission Denial: can't dump ConnectivityService " +
1667 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1668 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001669 return;
1670 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001671 pw.println();
1672 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001673 if (nst != null) {
1674 if (nst.getNetworkInfo().isConnected()) {
1675 pw.println("Active network: " + nst.getNetworkInfo().
1676 getTypeName());
1677 }
1678 pw.println(nst.getNetworkInfo());
1679 pw.println(nst);
1680 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001681 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001682 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001683
1684 pw.println("Network Requester Pids:");
1685 for (int net : mPriorityList) {
1686 String pidString = net + ": ";
1687 for (Object pid : mNetRequestersPids[net]) {
1688 pidString = pidString + pid.toString() + ", ";
1689 }
1690 pw.println(pidString);
1691 }
1692 pw.println();
1693
1694 pw.println("FeatureUsers:");
1695 for (Object requester : mFeatureUsers) {
1696 pw.println(requester.toString());
1697 }
1698 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001699
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001700 synchronized (this) {
1701 pw.println("NetworkTranstionWakeLock is currently " +
1702 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1703 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1704 }
1705 pw.println();
1706
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001707 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07001708
1709 if (mInetLog != null) {
1710 pw.println();
1711 pw.println("Inet condition reports:");
1712 for(int i = 0; i < mInetLog.size(); i++) {
1713 pw.println(mInetLog.get(i));
1714 }
1715 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001716 }
1717
Robert Greenwalt2034b912009-08-12 16:08:25 -07001718 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001719 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07001720 public MyHandler(Looper looper) {
1721 super(looper);
1722 }
1723
The Android Open Source Project28527d22009-03-03 19:31:44 -08001724 @Override
1725 public void handleMessage(Message msg) {
1726 NetworkInfo info;
1727 switch (msg.what) {
1728 case NetworkStateTracker.EVENT_STATE_CHANGED:
1729 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08001730 int type = info.getType();
1731 NetworkInfo.State state = info.getState();
Robert Greenwalt24e2d2b2010-01-25 16:14:00 -08001732 // only do this optimization for wifi. It going into scan mode for location
1733 // services generates alot of noise. Meanwhile the mms apn won't send out
1734 // subsequent notifications when on default cellular because it never
1735 // disconnects.. so only do this to wifi notifications. Fixed better when the
1736 // APN notifications are standardized.
1737 if (mNetAttributes[type].mLastState == state &&
1738 mNetAttributes[type].mRadio == ConnectivityManager.TYPE_WIFI) {
Robert Greenwalt12c44552009-12-07 11:33:18 -08001739 if (DBG) {
Robert Greenwalt24e2d2b2010-01-25 16:14:00 -08001740 // TODO - remove this after we validate the dropping doesn't break
1741 // anything
Joe Onoratoc2386bb2010-02-26 18:56:32 -08001742 Slog.d(TAG, "Dropping ConnectivityChange for " +
Robert Greenwalt2adbc7f2010-01-13 09:36:31 -08001743 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08001744 state + "/" + info.getDetailedState());
1745 }
1746 return;
1747 }
1748 mNetAttributes[type].mLastState = state;
1749
Joe Onoratoc2386bb2010-02-26 18:56:32 -08001750 if (DBG) Slog.d(TAG, "ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07001751 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08001752 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001753
1754 // Connectivity state changed:
1755 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07001756 // [12-9] Network subtype (for mobile network, as defined
1757 // by TelephonyManager)
1758 // [8-3] Detailed state ordinal (as defined by
1759 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001760 // [2-0] Network type (as defined by ConnectivityManager)
1761 int eventLogParam = (info.getType() & 0x7) |
1762 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1763 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08001764 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07001765 eventLogParam);
1766
1767 if (info.getDetailedState() ==
1768 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001769 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001770 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001771 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001772 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001773 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001774 // the logic here is, handle SUSPENDED the same as
1775 // DISCONNECTED. The only difference being we are
1776 // broadcasting an intent with NetworkInfo that's
1777 // suspended. This allows the applications an
1778 // opportunity to handle DISCONNECTED and SUSPENDED
1779 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001780 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001781 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001782 handleConnect(info);
1783 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001784 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001785 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001786 // TODO - make this handle ip/proxy/gateway/dns changes
1787 info = (NetworkInfo) msg.obj;
1788 type = info.getType();
1789 handleDnsConfigurationChange(type);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001790 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001791 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001792 String causedBy = null;
1793 synchronized (ConnectivityService.this) {
1794 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
1795 mNetTransitionWakeLock.isHeld()) {
1796 mNetTransitionWakeLock.release();
1797 causedBy = mNetTransitionWakeLockCausedBy;
1798 }
1799 }
1800 if (causedBy != null) {
1801 Slog.d(TAG, "NetTransition Wakelock for " +
1802 causedBy + " released by timeout");
1803 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07001804 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001805 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001806 FeatureUser u = (FeatureUser)msg.obj;
1807 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07001808 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001809 case EVENT_INET_CONDITION_CHANGE:
1810 {
1811 int netType = msg.arg1;
1812 int condition = msg.arg2;
1813 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001814 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001815 }
1816 case EVENT_INET_CONDITION_HOLD_END:
1817 {
1818 int netType = msg.arg1;
1819 int sequence = msg.arg2;
1820 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07001821 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001822 }
1823 case EVENT_SET_NETWORK_PREFERENCE:
1824 {
1825 int preference = msg.arg1;
1826 handleSetNetworkPreference(preference);
1827 break;
1828 }
1829 case EVENT_SET_BACKGROUND_DATA:
1830 {
1831 boolean enabled = (msg.arg1 == ENABLED);
1832 handleSetBackgroundData(enabled);
1833 break;
1834 }
1835 case EVENT_SET_MOBILE_DATA:
1836 {
1837 boolean enabled = (msg.arg1 == ENABLED);
1838 handleSetMobileData(enabled);
1839 break;
1840 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001841 }
1842 }
1843 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001844
1845 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08001846 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001847 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08001848
1849 if (isTetheringSupported()) {
1850 return mTethering.tether(iface);
1851 } else {
1852 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1853 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001854 }
1855
1856 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08001857 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001858 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08001859
1860 if (isTetheringSupported()) {
1861 return mTethering.untether(iface);
1862 } else {
1863 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1864 }
1865 }
1866
1867 // javadoc from interface
1868 public int getLastTetherError(String iface) {
1869 enforceTetherAccessPermission();
1870
1871 if (isTetheringSupported()) {
1872 return mTethering.getLastTetherError(iface);
1873 } else {
1874 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1875 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001876 }
1877
1878 // TODO - proper iface API for selection by property, inspection, etc
1879 public String[] getTetherableUsbRegexs() {
1880 enforceTetherAccessPermission();
1881 if (isTetheringSupported()) {
1882 return mTethering.getTetherableUsbRegexs();
1883 } else {
1884 return new String[0];
1885 }
1886 }
1887
1888 public String[] getTetherableWifiRegexs() {
1889 enforceTetherAccessPermission();
1890 if (isTetheringSupported()) {
1891 return mTethering.getTetherableWifiRegexs();
1892 } else {
1893 return new String[0];
1894 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001895 }
1896
Danica Chang96567052010-08-11 14:54:43 -07001897 public String[] getTetherableBluetoothRegexs() {
1898 enforceTetherAccessPermission();
1899 if (isTetheringSupported()) {
1900 return mTethering.getTetherableBluetoothRegexs();
1901 } else {
1902 return new String[0];
1903 }
1904 }
1905
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001906 // TODO - move iface listing, queries, etc to new module
1907 // javadoc from interface
1908 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001909 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001910 return mTethering.getTetherableIfaces();
1911 }
1912
1913 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001914 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001915 return mTethering.getTetheredIfaces();
1916 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001917
Robert Greenwalt4283ded2010-03-02 17:25:02 -08001918 public String[] getTetheringErroredIfaces() {
1919 enforceTetherAccessPermission();
1920 return mTethering.getErroredIfaces();
1921 }
1922
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001923 // if ro.tether.denied = true we default to no tethering
1924 // gservices could set the secure setting to 1 though to enable it on a build where it
1925 // had previously been turned off.
1926 public boolean isTetheringSupported() {
1927 enforceTetherAccessPermission();
1928 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08001929 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
1930 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
1931 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001932 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001933
1934 // An API NetworkStateTrackers can call when they lose their network.
1935 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
1936 // whichever happens first. The timer is started by the first caller and not
1937 // restarted by subsequent callers.
1938 public void requestNetworkTransitionWakelock(String forWhom) {
1939 enforceConnectivityInternalPermission();
1940 synchronized (this) {
1941 if (mNetTransitionWakeLock.isHeld()) return;
1942 mNetTransitionWakeLockSerialNumber++;
1943 mNetTransitionWakeLock.acquire();
1944 mNetTransitionWakeLockCausedBy = forWhom;
1945 }
1946 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001947 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001948 mNetTransitionWakeLockSerialNumber, 0),
1949 mNetTransitionWakeLockTimeout);
1950 return;
1951 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07001952
Robert Greenwalt986c7412010-09-08 15:24:47 -07001953 // 100 percent is full good, 0 is full bad.
1954 public void reportInetCondition(int networkType, int percentage) {
1955 if (DBG) Slog.d(TAG, "reportNetworkCondition(" + networkType + ", " + percentage + ")");
1956 mContext.enforceCallingOrSelfPermission(
1957 android.Manifest.permission.STATUS_BAR,
1958 "ConnectivityService");
1959
Robert Greenwalt0e80be12010-09-20 14:35:25 -07001960 if (DBG) {
1961 int pid = getCallingPid();
1962 int uid = getCallingUid();
1963 String s = pid + "(" + uid + ") reports inet is " +
1964 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
1965 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
1966 mInetLog.add(s);
1967 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
1968 mInetLog.remove(0);
1969 }
1970 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001971 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001972 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
1973 }
1974
1975 private void handleInetConditionChange(int netType, int condition) {
1976 if (DBG) {
1977 Slog.d(TAG, "Inet connectivity change, net=" +
1978 netType + ", condition=" + condition +
1979 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
1980 }
1981 if (mActiveDefaultNetwork == -1) {
1982 if (DBG) Slog.d(TAG, "no active default network - aborting");
1983 return;
1984 }
1985 if (mActiveDefaultNetwork != netType) {
1986 if (DBG) Slog.d(TAG, "given net not default - aborting");
1987 return;
1988 }
1989 mDefaultInetCondition = condition;
1990 int delay;
1991 if (mInetConditionChangeInFlight == false) {
1992 if (DBG) Slog.d(TAG, "starting a change hold");
1993 // setup a new hold to debounce this
1994 if (mDefaultInetCondition > 50) {
1995 delay = Settings.Secure.getInt(mContext.getContentResolver(),
1996 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
1997 } else {
1998 delay = Settings.Secure.getInt(mContext.getContentResolver(),
1999 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2000 }
2001 mInetConditionChangeInFlight = true;
2002 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2003 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2004 } else {
2005 // we've set the new condition, when this hold ends that will get
2006 // picked up
2007 if (DBG) Slog.d(TAG, "currently in hold - not setting new end evt");
2008 }
2009 }
2010
2011 private void handleInetConditionHoldEnd(int netType, int sequence) {
2012 if (DBG) {
2013 Slog.d(TAG, "Inet hold end, net=" + netType +
2014 ", condition =" + mDefaultInetCondition +
2015 ", published condition =" + mDefaultInetConditionPublished);
2016 }
2017 mInetConditionChangeInFlight = false;
2018
2019 if (mActiveDefaultNetwork == -1) {
2020 if (DBG) Slog.d(TAG, "no active default network - aborting");
2021 return;
2022 }
2023 if (mDefaultConnectionSequence != sequence) {
2024 if (DBG) Slog.d(TAG, "event hold for obsolete network - aborting");
2025 return;
2026 }
2027 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2028 if (DBG) Slog.d(TAG, "no change in condition - aborting");
2029 return;
2030 }
2031 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2032 if (networkInfo.isConnected() == false) {
2033 if (DBG) Slog.d(TAG, "default network not connected - aborting");
2034 return;
2035 }
2036 mDefaultInetConditionPublished = mDefaultInetCondition;
2037 sendInetConditionBroadcast(networkInfo);
2038 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002039 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002040}