blob: 33df76c3504b05b2392c2722bc88ab4d8612800c [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import android.app.Notification;
20import android.app.NotificationManager;
21import android.content.ContentResolver;
22import android.content.Context;
23import android.content.Intent;
24import android.content.pm.PackageManager;
25import android.net.ConnectivityManager;
26import android.net.IConnectivityManager;
27import android.net.MobileDataStateTracker;
28import android.net.NetworkInfo;
29import android.net.NetworkStateTracker;
30import android.net.wifi.WifiStateTracker;
Irfan Sheriffd649c122010-06-09 15:39:36 -070031import android.net.NetworkUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.os.Binder;
33import android.os.Handler;
Robert Greenwalt42acef32009-08-12 16:08:25 -070034import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.os.Looper;
36import android.os.Message;
Robert Greenwalt42acef32009-08-12 16:08:25 -070037import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.ServiceManager;
39import android.os.SystemProperties;
40import android.provider.Settings;
Robert Greenwalt42acef32009-08-12 16:08:25 -070041import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080043import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044
Robert Greenwalt42acef32009-08-12 16:08:25 -070045import com.android.internal.telephony.Phone;
46
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080047import com.android.server.connectivity.Tethering;
48
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -070050import java.io.FileWriter;
51import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import java.io.PrintWriter;
Robert Greenwalt42acef32009-08-12 16:08:25 -070053import java.util.ArrayList;
54import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055
56/**
57 * @hide
58 */
59public class ConnectivityService extends IConnectivityManager.Stub {
60
Robert Greenwaltd8df1492009-10-06 14:12:53 -070061 private static final boolean DBG = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 private static final String TAG = "ConnectivityService";
63
Robert Greenwalt42acef32009-08-12 16:08:25 -070064 // how long to wait before switching back to a radio's default network
65 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
66 // system property that can override the above value
67 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
68 "android.telephony.apn-restore";
69
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080070
71 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -080072 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 /**
75 * Sometimes we want to refer to the individual network state
76 * trackers separately, and sometimes we just want to treat them
77 * abstractly.
78 */
79 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -070080
81 /**
82 * A per Net list of the PID's that requested access to the net
83 * used both as a refcount and for per-PID DNS selection
84 */
85 private List mNetRequestersPids[];
86
Robert Greenwalt42acef32009-08-12 16:08:25 -070087 // priority order of the nettrackers
88 // (excluding dynamically set mNetworkPreference)
89 // TODO - move mNetworkTypePreference into this
90 private int[] mPriorityList;
91
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 private Context mContext;
93 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -070094 private int mActiveDefaultNetwork = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095
96 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
98 private boolean mTestMode;
99 private static ConnectivityService sServiceInstance;
100
Robert Greenwalt42acef32009-08-12 16:08:25 -0700101 private Handler mHandler;
102
103 // list of DeathRecipients used to make sure features are turned off when
104 // a process dies
105 private List mFeatureUsers;
106
Mike Lockwood0f79b542009-08-14 14:18:49 -0400107 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800108 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400109
Robert Greenwalt511288a2009-12-07 11:33:18 -0800110 private static class NetworkAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700111 /**
112 * Class for holding settings read from resources.
113 */
114 public String mName;
115 public int mType;
116 public int mRadio;
117 public int mPriority;
Robert Greenwalt511288a2009-12-07 11:33:18 -0800118 public NetworkInfo.State mLastState;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700119 public NetworkAttributes(String init) {
120 String fragments[] = init.split(",");
121 mName = fragments[0].toLowerCase();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700122 mType = Integer.parseInt(fragments[1]);
123 mRadio = Integer.parseInt(fragments[2]);
124 mPriority = Integer.parseInt(fragments[3]);
Robert Greenwalt511288a2009-12-07 11:33:18 -0800125 mLastState = NetworkInfo.State.UNKNOWN;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700126 }
127 public boolean isDefault() {
128 return (mType == mRadio);
129 }
130 }
131 NetworkAttributes[] mNetAttributes;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700132 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700133
Robert Greenwalt511288a2009-12-07 11:33:18 -0800134 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700135 public int mSimultaneity;
136 public int mType;
137 public RadioAttributes(String init) {
138 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700139 mType = Integer.parseInt(fragments[0]);
140 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700141 }
142 }
143 RadioAttributes[] mRadioAttributes;
144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 private static class ConnectivityThread extends Thread {
146 private Context mContext;
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 private ConnectivityThread(Context context) {
149 super("ConnectivityThread");
150 mContext = context;
151 }
152
153 @Override
154 public void run() {
155 Looper.prepare();
156 synchronized (this) {
157 sServiceInstance = new ConnectivityService(mContext);
158 notifyAll();
159 }
160 Looper.loop();
161 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 public static ConnectivityService getServiceInstance(Context context) {
164 ConnectivityThread thread = new ConnectivityThread(context);
165 thread.start();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 synchronized (thread) {
168 while (sServiceInstance == null) {
169 try {
170 // Wait until sServiceInstance has been initialized.
171 thread.wait();
172 } catch (InterruptedException ignore) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800173 Slog.e(TAG,
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700174 "Unexpected InterruptedException while waiting"+
175 " for ConnectivityService thread");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 }
177 }
178 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 return sServiceInstance;
181 }
182 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 public static ConnectivityService getInstance(Context context) {
185 return ConnectivityThread.getServiceInstance(context);
186 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 private ConnectivityService(Context context) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800189 if (DBG) Slog.v(TAG, "ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800190
191 // setup our unique device name
192 String id = Settings.Secure.getString(context.getContentResolver(),
193 Settings.Secure.ANDROID_ID);
194 if (id != null && id.length() > 0) {
195 String name = new String("android_").concat(id);
196 SystemProperties.set("net.hostname", name);
197 }
198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 mContext = context;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700200 mNetTrackers = new NetworkStateTracker[
201 ConnectivityManager.MAX_NETWORK_TYPE+1];
202 mHandler = new MyHandler();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700205
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700206 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
207 mNetAttributes = new NetworkAttributes[ConnectivityManager.MAX_NETWORK_TYPE+1];
208
Robert Greenwalt42acef32009-08-12 16:08:25 -0700209 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700210 String[] raStrings = context.getResources().getStringArray(
211 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700212 for (String raString : raStrings) {
213 RadioAttributes r = new RadioAttributes(raString);
214 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800215 Slog.e(TAG, "Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700216 continue;
217 }
218 if (mRadioAttributes[r.mType] != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800219 Slog.e(TAG, "Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700220 r.mType);
221 continue;
222 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700223 mRadioAttributes[r.mType] = r;
224 }
225
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700226 String[] naStrings = context.getResources().getStringArray(
227 com.android.internal.R.array.networkAttributes);
228 for (String naString : naStrings) {
229 try {
230 NetworkAttributes n = new NetworkAttributes(naString);
231 if (n.mType > ConnectivityManager.MAX_NETWORK_TYPE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800232 Slog.e(TAG, "Error in networkAttributes - ignoring attempt to define type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700233 n.mType);
234 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700235 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700236 if (mNetAttributes[n.mType] != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800237 Slog.e(TAG, "Error in networkAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700238 n.mType);
239 continue;
240 }
241 if (mRadioAttributes[n.mRadio] == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800242 Slog.e(TAG, "Error in networkAttributes - ignoring attempt to use undefined " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700243 "radio " + n.mRadio + " in network type " + n.mType);
244 continue;
245 }
246 mNetAttributes[n.mType] = n;
247 mNetworksDefined++;
248 } catch(Exception e) {
249 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700250 }
251 }
252
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700253 // high priority first
254 mPriorityList = new int[mNetworksDefined];
255 {
256 int insertionPoint = mNetworksDefined-1;
257 int currentLowest = 0;
258 int nextLowest = 0;
259 while (insertionPoint > -1) {
260 for (NetworkAttributes na : mNetAttributes) {
261 if (na == null) continue;
262 if (na.mPriority < currentLowest) continue;
263 if (na.mPriority > currentLowest) {
264 if (na.mPriority < nextLowest || nextLowest == 0) {
265 nextLowest = na.mPriority;
266 }
267 continue;
268 }
269 mPriorityList[insertionPoint--] = na.mType;
270 }
271 currentLowest = nextLowest;
272 nextLowest = 0;
273 }
274 }
275
276 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
277 for (int i : mPriorityList) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700278 mNetRequestersPids[i] = new ArrayList();
279 }
280
281 mFeatureUsers = new ArrayList();
282
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700283 mNumDnsEntries = 0;
284
285 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
286 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 /*
288 * Create the network state trackers for Wi-Fi and mobile
289 * data. Maybe this could be done with a factory class,
290 * but it's not clear that it's worth it, given that
291 * the number of different network types is not going
292 * to change very often.
293 */
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800294 boolean noMobileData = !getMobileDataEnabled();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700295 for (int netType : mPriorityList) {
296 switch (mNetAttributes[netType].mRadio) {
297 case ConnectivityManager.TYPE_WIFI:
Joe Onorato8a9b2202010-02-26 18:56:32 -0800298 if (DBG) Slog.v(TAG, "Starting Wifi Service.");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700299 WifiStateTracker wst = new WifiStateTracker(context, mHandler);
300 WifiService wifiService = new WifiService(context, wst);
301 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff7b009782010-03-11 16:37:45 -0800302 wifiService.startWifi();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700303 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
304 wst.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700306 break;
307 case ConnectivityManager.TYPE_MOBILE:
308 mNetTrackers[netType] = new MobileDataStateTracker(context, mHandler,
309 netType, mNetAttributes[netType].mName);
310 mNetTrackers[netType].startMonitoring();
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800311 if (noMobileData) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800312 if (DBG) Slog.d(TAG, "tearing down Mobile networks due to setting");
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800313 mNetTrackers[netType].teardown();
314 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700315 break;
316 default:
Joe Onorato8a9b2202010-02-26 18:56:32 -0800317 Slog.e(TAG, "Trying to create a DataStateTracker for an unknown radio type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700318 mNetAttributes[netType].mRadio);
319 continue;
320 }
321 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800322
Robert Greenwaltdfadaea2010-03-11 15:03:08 -0800323 mTethering = new Tethering(mContext, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800324 mTetheringConfigValid = (((mNetTrackers[ConnectivityManager.TYPE_MOBILE_DUN] != null) ||
325 !mTethering.isDunRequired()) &&
326 (mTethering.getTetherableUsbRegexs().length != 0 ||
327 mTethering.getTetherableWifiRegexs().length != 0) &&
328 mTethering.getUpstreamIfaceRegexs().length != 0);
329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 }
331
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700334 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 * @param preference the new preference
336 */
337 public synchronized void setNetworkPreference(int preference) {
338 enforceChangePermission();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700339 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700340 mNetAttributes[preference] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700341 mNetAttributes[preference].isDefault()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 if (mNetworkPreference != preference) {
343 persistNetworkPreference(preference);
344 mNetworkPreference = preference;
345 enforcePreference();
346 }
347 }
348 }
349
350 public int getNetworkPreference() {
351 enforceAccessPermission();
352 return mNetworkPreference;
353 }
354
355 private void persistNetworkPreference(int networkPreference) {
356 final ContentResolver cr = mContext.getContentResolver();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700357 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE,
358 networkPreference);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 private int getPersistedNetworkPreference() {
362 final ContentResolver cr = mContext.getContentResolver();
363
364 final int networkPrefSetting = Settings.Secure
365 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
366 if (networkPrefSetting != -1) {
367 return networkPrefSetting;
368 }
369
370 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
371 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700374 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 * In this method, we only tear down a non-preferred network. Establishing
376 * a connection to the preferred network is taken care of when we handle
377 * the disconnect event from the non-preferred network
378 * (see {@link #handleDisconnect(NetworkInfo)}).
379 */
380 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700381 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 return;
383
Robert Greenwalt42acef32009-08-12 16:08:25 -0700384 if (!mNetTrackers[mNetworkPreference].isAvailable())
385 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386
Robert Greenwalt42acef32009-08-12 16:08:25 -0700387 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700388 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700389 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700390 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800391 Slog.d(TAG, "tearing down " +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700392 mNetTrackers[t].getNetworkInfo() +
393 " in enforcePreference");
394 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700395 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 }
397 }
398 }
399
400 private boolean teardown(NetworkStateTracker netTracker) {
401 if (netTracker.teardown()) {
402 netTracker.setTeardownRequested(true);
403 return true;
404 } else {
405 return false;
406 }
407 }
408
409 /**
410 * Return NetworkInfo for the active (i.e., connected) network interface.
411 * It is assumed that at most one network is active at a time. If more
412 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700413 * @return the info for the active network, or {@code null} if none is
414 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 */
416 public NetworkInfo getActiveNetworkInfo() {
417 enforceAccessPermission();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700418 for (int type=0; type <= ConnectivityManager.MAX_NETWORK_TYPE; type++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700419 if (mNetAttributes[type] == null || !mNetAttributes[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700420 continue;
421 }
422 NetworkStateTracker t = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 NetworkInfo info = t.getNetworkInfo();
424 if (info.isConnected()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800425 if (DBG && type != mActiveDefaultNetwork) Slog.e(TAG,
Robert Greenwalt42acef32009-08-12 16:08:25 -0700426 "connected default network is not " +
427 "mActiveDefaultNetwork!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 return info;
429 }
430 }
431 return null;
432 }
433
434 public NetworkInfo getNetworkInfo(int networkType) {
435 enforceAccessPermission();
436 if (ConnectivityManager.isNetworkTypeValid(networkType)) {
437 NetworkStateTracker t = mNetTrackers[networkType];
438 if (t != null)
439 return t.getNetworkInfo();
440 }
441 return null;
442 }
443
444 public NetworkInfo[] getAllNetworkInfo() {
445 enforceAccessPermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700446 NetworkInfo[] result = new NetworkInfo[mNetworksDefined];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 int i = 0;
448 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700449 if(t != null) result[i++] = t.getNetworkInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 }
451 return result;
452 }
453
454 public boolean setRadios(boolean turnOn) {
455 boolean result = true;
456 enforceChangePermission();
457 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700458 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 }
460 return result;
461 }
462
463 public boolean setRadio(int netType, boolean turnOn) {
464 enforceChangePermission();
465 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
466 return false;
467 }
468 NetworkStateTracker tracker = mNetTrackers[netType];
469 return tracker != null && tracker.setRadio(turnOn);
470 }
471
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700472 /**
473 * Used to notice when the calling process dies so we can self-expire
474 *
475 * Also used to know if the process has cleaned up after itself when
476 * our auto-expire timer goes off. The timer has a link to an object.
477 *
478 */
Robert Greenwalt42acef32009-08-12 16:08:25 -0700479 private class FeatureUser implements IBinder.DeathRecipient {
480 int mNetworkType;
481 String mFeature;
482 IBinder mBinder;
483 int mPid;
484 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -0800485 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700486
487 FeatureUser(int type, String feature, IBinder binder) {
488 super();
489 mNetworkType = type;
490 mFeature = feature;
491 mBinder = binder;
492 mPid = getCallingPid();
493 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -0800494 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700495
Robert Greenwalt42acef32009-08-12 16:08:25 -0700496 try {
497 mBinder.linkToDeath(this, 0);
498 } catch (RemoteException e) {
499 binderDied();
500 }
501 }
502
503 void unlinkDeathRecipient() {
504 mBinder.unlinkToDeath(this, 0);
505 }
506
507 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800508 Slog.d(TAG, "ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800509 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
510 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700511 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700512 }
513
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700514 public void expire() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800515 Slog.d(TAG, "ConnectivityService FeatureUser expire(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800516 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
517 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700518 stopUsingNetworkFeature(this, false);
519 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800520
521 public String toString() {
522 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
523 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
524 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700525 }
526
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700527 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700528 public int startUsingNetworkFeature(int networkType, String feature,
529 IBinder binder) {
530 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800531 Slog.d(TAG, "startUsingNetworkFeature for net " + networkType +
Robert Greenwalt42acef32009-08-12 16:08:25 -0700532 ": " + feature);
533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700535 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
536 mNetAttributes[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700537 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700539
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700540 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700541
542 // TODO - move this into the MobileDataStateTracker
543 int usedNetworkType = networkType;
544 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800545 if (!getMobileDataEnabled()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800546 if (DBG) Slog.d(TAG, "requested special network with data disabled - rejected");
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800547 return Phone.APN_TYPE_NOT_AVAILABLE;
548 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700549 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
550 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
551 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
552 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
553 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN)) {
554 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
555 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
556 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
557 }
558 }
559 NetworkStateTracker network = mNetTrackers[usedNetworkType];
560 if (network != null) {
561 if (usedNetworkType != networkType) {
562 Integer currentPid = new Integer(getCallingPid());
563
564 NetworkStateTracker radio = mNetTrackers[networkType];
565 NetworkInfo ni = network.getNetworkInfo();
566
567 if (ni.isAvailable() == false) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800568 if (DBG) Slog.d(TAG, "special network not available");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700569 return Phone.APN_TYPE_NOT_AVAILABLE;
570 }
571
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700572 synchronized(this) {
573 mFeatureUsers.add(f);
574 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
575 // this gets used for per-pid dns when connected
576 mNetRequestersPids[usedNetworkType].add(currentPid);
577 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700578 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700579 mHandler.sendMessageDelayed(mHandler.obtainMessage(
580 NetworkStateTracker.EVENT_RESTORE_DEFAULT_NETWORK,
581 f), getRestoreDefaultNetworkDelay());
582
Robert Greenwalt42acef32009-08-12 16:08:25 -0700583
Robert Greenwalta64bf832009-08-19 20:19:33 -0700584 if ((ni.isConnectedOrConnecting() == true) &&
585 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700586 if (ni.isConnected() == true) {
587 // add the pid-specific dns
588 handleDnsConfigurationChange();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800589 if (DBG) Slog.d(TAG, "special network already active");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700590 return Phone.APN_ALREADY_ACTIVE;
591 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800592 if (DBG) Slog.d(TAG, "special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700593 return Phone.APN_REQUEST_STARTED;
594 }
595
596 // check if the radio in play can make another contact
597 // assume if cannot for now
598
Joe Onorato8a9b2202010-02-26 18:56:32 -0800599 if (DBG) Slog.d(TAG, "reconnecting to special network");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700600 network.reconnect();
601 return Phone.APN_REQUEST_STARTED;
602 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -0700603 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700604 }
605 }
606 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 }
608
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700609 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700611 enforceChangePermission();
612
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700613 int pid = getCallingPid();
614 int uid = getCallingUid();
615
616 FeatureUser u = null;
617 boolean found = false;
618
619 synchronized(this) {
620 for (int i = 0; i < mFeatureUsers.size() ; i++) {
621 u = (FeatureUser)mFeatureUsers.get(i);
622 if (uid == u.mUid && pid == u.mPid &&
623 networkType == u.mNetworkType &&
624 TextUtils.equals(feature, u.mFeature)) {
625 found = true;
626 break;
627 }
628 }
629 }
630 if (found && u != null) {
631 // stop regardless of how many other time this proc had called start
632 return stopUsingNetworkFeature(u, true);
633 } else {
634 // none found!
Joe Onorato8a9b2202010-02-26 18:56:32 -0800635 if (DBG) Slog.d(TAG, "ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700636 return 1;
637 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700638 }
639
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700640 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
641 int networkType = u.mNetworkType;
642 String feature = u.mFeature;
643 int pid = u.mPid;
644 int uid = u.mUid;
645
646 NetworkStateTracker tracker = null;
647 boolean callTeardown = false; // used to carry our decision outside of sync block
648
Robert Greenwalt42acef32009-08-12 16:08:25 -0700649 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800650 Slog.d(TAG, "stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt42acef32009-08-12 16:08:25 -0700651 ": " + feature);
652 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
655 return -1;
656 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700657
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700658 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
659 // sync block
660 synchronized(this) {
661 // check if this process still has an outstanding start request
662 if (!mFeatureUsers.contains(u)) {
Robert Greenwalt78a640a2010-03-10 16:10:43 -0800663 if (DBG) Slog.d(TAG, "ignoring - this process has no outstanding requests");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700664 return 1;
665 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700666 u.unlinkDeathRecipient();
667 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
668 // If we care about duplicate requests, check for that here.
669 //
670 // This is done to support the extension of a request - the app
671 // can request we start the network feature again and renew the
672 // auto-shutoff delay. Normal "stop" calls from the app though
673 // do not pay attention to duplicate requests - in effect the
674 // API does not refcount and a single stop will counter multiple starts.
675 if (ignoreDups == false) {
676 for (int i = 0; i < mFeatureUsers.size() ; i++) {
677 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
678 if (x.mUid == u.mUid && x.mPid == u.mPid &&
679 x.mNetworkType == u.mNetworkType &&
680 TextUtils.equals(x.mFeature, u.mFeature)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800681 if (DBG) Slog.d(TAG, "ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700682 return 1;
683 }
684 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700685 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700686
687 // TODO - move to MobileDataStateTracker
688 int usedNetworkType = networkType;
689 if (networkType == ConnectivityManager.TYPE_MOBILE) {
690 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
691 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
692 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
693 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
694 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN)) {
695 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
696 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
697 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
698 }
699 }
700 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700701 if (tracker == null) {
Robert Greenwalt78a640a2010-03-10 16:10:43 -0800702 if (DBG) Slog.d(TAG, "ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700703 return -1;
704 }
705 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700706 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700707 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -0800708 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700709 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800710 if (DBG) Slog.d(TAG, "not tearing down special network - " +
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700711 "others still using it");
712 return 1;
713 }
714 callTeardown = true;
715 }
716 }
Robert Greenwalt78a640a2010-03-10 16:10:43 -0800717 if (DBG) Slog.d(TAG, "Doing network teardown");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700718 if (callTeardown) {
719 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700720 return 1;
721 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -0700722 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 }
725
726 /**
727 * Ensure that a network route exists to deliver traffic to the specified
728 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700729 * @param networkType the type of the network over which traffic to the
730 * specified host is to be routed
731 * @param hostAddress the IP address of the host to which the route is
732 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 * @return {@code true} on success, {@code false} on failure
734 */
735 public boolean requestRouteToHost(int networkType, int hostAddress) {
736 enforceChangePermission();
737 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
738 return false;
739 }
740 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -0700741
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700742 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
743 tracker.isTeardownRequested()) {
Robert Greenwalt8206ff32009-09-10 15:06:20 -0700744 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800745 Slog.d(TAG, "requestRouteToHost on down network (" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -0700746 }
747 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 }
Irfan Sheriffd649c122010-06-09 15:39:36 -0700749 return addHostRoute(tracker, hostAddress);
750 }
751
752 /**
753 * Ensure that a network route exists to deliver traffic to the specified
754 * host via the mobile data network.
755 * @param hostAddress the IP address of the host to which the route is desired,
756 * in network byte order.
757 * @return {@code true} on success, {@code false} on failure
758 */
759 private boolean addHostRoute(NetworkStateTracker nt, int hostAddress) {
760 if (nt.getNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI) {
761 return false;
762 }
763
764 String interfaceName = nt.getInterfaceName();
765
766 if (DBG) {
767 Slog.d(TAG, "Requested host route to " + Integer.toHexString(hostAddress) +
768 "(" + interfaceName + ")");
769 }
770 if (interfaceName != null && hostAddress != -1) {
771 return NetworkUtils.addHostRoute(interfaceName, hostAddress) == 0;
772 } else {
773 return false;
774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 }
776
777 /**
778 * @see ConnectivityManager#getBackgroundDataSetting()
779 */
780 public boolean getBackgroundDataSetting() {
781 return Settings.Secure.getInt(mContext.getContentResolver(),
782 Settings.Secure.BACKGROUND_DATA, 1) == 1;
783 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 /**
786 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
787 */
788 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
789 mContext.enforceCallingOrSelfPermission(
790 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
791 "ConnectivityService");
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 if (getBackgroundDataSetting() == allowBackgroundDataUsage) return;
794
795 Settings.Secure.putInt(mContext.getContentResolver(),
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700796 Settings.Secure.BACKGROUND_DATA,
797 allowBackgroundDataUsage ? 1 : 0);
798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 Intent broadcast = new Intent(
800 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
801 mContext.sendBroadcast(broadcast);
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700802 }
803
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800804 /**
805 * @see ConnectivityManager#getMobileDataEnabled()
806 */
807 public boolean getMobileDataEnabled() {
808 enforceAccessPermission();
809 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
810 Settings.Secure.MOBILE_DATA, 1) == 1;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800811 if (DBG) Slog.d(TAG, "getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800812 return retVal;
813 }
814
815 /**
816 * @see ConnectivityManager#setMobileDataEnabled(boolean)
817 */
818 public synchronized void setMobileDataEnabled(boolean enabled) {
819 enforceChangePermission();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800820 if (DBG) Slog.d(TAG, "setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800821
822 if (getMobileDataEnabled() == enabled) return;
823
824 Settings.Secure.putInt(mContext.getContentResolver(),
825 Settings.Secure.MOBILE_DATA, enabled ? 1 : 0);
826
827 if (enabled) {
828 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800829 if (DBG) Slog.d(TAG, "starting up " + mNetTrackers[ConnectivityManager.TYPE_MOBILE]);
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800830 mNetTrackers[ConnectivityManager.TYPE_MOBILE].reconnect();
831 }
832 } else {
833 for (NetworkStateTracker nt : mNetTrackers) {
834 if (nt == null) continue;
835 int netType = nt.getNetworkInfo().getType();
836 if (mNetAttributes[netType].mRadio == ConnectivityManager.TYPE_MOBILE) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800837 if (DBG) Slog.d(TAG, "tearing down " + nt);
Robert Greenwaltc03fa502010-02-23 18:58:05 -0800838 nt.teardown();
839 }
840 }
841 }
842 }
843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 private int getNumConnectedNetworks() {
845 int numConnectedNets = 0;
846
847 for (NetworkStateTracker nt : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700848 if (nt != null && nt.getNetworkInfo().isConnected() &&
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700849 !nt.isTeardownRequested()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 ++numConnectedNets;
851 }
852 }
853 return numConnectedNets;
854 }
855
856 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700857 mContext.enforceCallingOrSelfPermission(
858 android.Manifest.permission.ACCESS_NETWORK_STATE,
859 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 }
861
862 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700863 mContext.enforceCallingOrSelfPermission(
864 android.Manifest.permission.CHANGE_NETWORK_STATE,
865 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 }
867
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800868 // TODO Make this a special check when it goes public
869 private void enforceTetherChangePermission() {
870 mContext.enforceCallingOrSelfPermission(
871 android.Manifest.permission.CHANGE_NETWORK_STATE,
872 "ConnectivityService");
873 }
874
Robert Greenwalt2a091d72010-02-11 18:18:40 -0800875 private void enforceTetherAccessPermission() {
876 mContext.enforceCallingOrSelfPermission(
877 android.Manifest.permission.ACCESS_NETWORK_STATE,
878 "ConnectivityService");
879 }
880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700882 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
883 * network, we ignore it. If it is for the active network, we send out a
884 * broadcast. But first, we check whether it might be possible to connect
885 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 * @param info the {@code NetworkInfo} for the network
887 */
888 private void handleDisconnect(NetworkInfo info) {
889
Robert Greenwalt42acef32009-08-12 16:08:25 -0700890 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891
Robert Greenwalt42acef32009-08-12 16:08:25 -0700892 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 /*
894 * If the disconnected network is not the active one, then don't report
895 * this as a loss of connectivity. What probably happened is that we're
896 * getting the disconnect for a network that we explicitly disabled
897 * in accordance with network preference policies.
898 */
Robert Greenwalt42acef32009-08-12 16:08:25 -0700899 if (!mNetAttributes[prevNetType].isDefault()) {
900 List pids = mNetRequestersPids[prevNetType];
901 for (int i = 0; i<pids.size(); i++) {
902 Integer pid = (Integer)pids.get(i);
903 // will remove them because the net's no longer connected
904 // need to do this now as only now do we know the pids and
905 // can properly null things that are no longer referenced.
906 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 }
909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800911 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
913 if (info.isFailover()) {
914 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
915 info.setFailover(false);
916 }
917 if (info.getReason() != null) {
918 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
919 }
920 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700921 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
922 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700924
Robert Greenwaltcc4b4012010-01-25 17:54:29 -0800925 NetworkStateTracker newNet = null;
926 if (mNetAttributes[prevNetType].isDefault()) {
927 newNet = tryFailover(prevNetType);
928 if (newNet != null) {
929 NetworkInfo switchTo = newNet.getNetworkInfo();
930 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
931 } else {
932 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
933 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -0800934 }
935 // do this before we broadcast the change
936 handleConnectivityChange();
937
938 sendStickyBroadcast(intent);
939 /*
940 * If the failover network is already connected, then immediately send
941 * out a followup broadcast indicating successful failover
942 */
943 if (newNet != null && newNet.getNetworkInfo().isConnected()) {
944 sendConnectedBroadcast(newNet.getNetworkInfo());
945 }
946 }
947
Robert Greenwaltcc4b4012010-01-25 17:54:29 -0800948 // returns null if no failover available
Robert Greenwaltda03c4e2010-01-20 19:29:41 -0800949 private NetworkStateTracker tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700950 /*
951 * If this is a default network, check if other defaults are available
952 * or active
953 */
954 NetworkStateTracker newNet = null;
955 if (mNetAttributes[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700956 if (mActiveDefaultNetwork == prevNetType) {
957 mActiveDefaultNetwork = -1;
958 }
959
960 int newType = -1;
961 int newPriority = -1;
Robert Greenwalt35429592010-02-25 12:04:29 -0800962 boolean noMobileData = !getMobileDataEnabled();
Robert Greenwaltda03c4e2010-01-20 19:29:41 -0800963 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700964 if (checkType == prevNetType) continue;
965 if (mNetAttributes[checkType] == null) continue;
Robert Greenwalt35429592010-02-25 12:04:29 -0800966 if (mNetAttributes[checkType].mRadio == ConnectivityManager.TYPE_MOBILE &&
967 noMobileData) {
968 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800969 Slog.d(TAG, "not failing over to mobile type " + checkType +
Robert Greenwalt35429592010-02-25 12:04:29 -0800970 " because Mobile Data Disabled");
971 }
972 continue;
973 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700974 if (mNetAttributes[checkType].isDefault()) {
975 /* TODO - if we have multiple nets we could use
976 * we may want to put more thought into which we choose
977 */
978 if (checkType == mNetworkPreference) {
979 newType = checkType;
980 break;
981 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700982 if (mNetAttributes[checkType].mPriority > newPriority) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700983 newType = checkType;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700984 newPriority = mNetAttributes[newType].mPriority;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 }
987 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700988
989 if (newType != -1) {
990 newNet = mNetTrackers[newType];
991 /**
992 * See if the other network is available to fail over to.
993 * If is not available, we enable it anyway, so that it
994 * will be able to connect when it does become available,
995 * but we report a total loss of connectivity rather than
996 * report that we are attempting to fail over.
997 */
998 if (newNet.isAvailable()) {
999 NetworkInfo switchTo = newNet.getNetworkInfo();
1000 switchTo.setFailover(true);
Robert Greenwalta64bf832009-08-19 20:19:33 -07001001 if (!switchTo.isConnectedOrConnecting() ||
1002 newNet.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001003 newNet.reconnect();
1004 }
1005 if (DBG) {
1006 if (switchTo.isConnected()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001007 Slog.v(TAG, "Switching to already connected " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001008 switchTo.getTypeName());
1009 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001010 Slog.v(TAG, "Attempting to switch to " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001011 switchTo.getTypeName());
1012 }
1013 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001014 } else {
1015 newNet.reconnect();
Robert Greenwaltf0fa39e2010-03-09 14:55:08 -08001016 newNet = null; // not officially avail.. try anyway, but
1017 // report no failover
Robert Greenwalt42acef32009-08-12 16:08:25 -07001018 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001021
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001022 return newNet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 }
1024
1025 private void sendConnectedBroadcast(NetworkInfo info) {
1026 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001027 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1029 if (info.isFailover()) {
1030 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1031 info.setFailover(false);
1032 }
1033 if (info.getReason() != null) {
1034 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1035 }
1036 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001037 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1038 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001040 sendStickyBroadcast(intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 }
1042
1043 /**
1044 * Called when an attempt to fail over to another network has failed.
1045 * @param info the {@link NetworkInfo} for the failed network
1046 */
1047 private void handleConnectionFailure(NetworkInfo info) {
1048 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049
Robert Greenwalt42acef32009-08-12 16:08:25 -07001050 String reason = info.getReason();
1051 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001052
Robert Greenwalt42acef32009-08-12 16:08:25 -07001053 if (DBG) {
1054 String reasonText;
1055 if (reason == null) {
1056 reasonText = ".";
1057 } else {
1058 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001060 Slog.v(TAG, "Attempt to connect to " + info.getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001061 " failed" + reasonText);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001063
1064 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001065 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001066 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1067 if (getActiveNetworkInfo() == null) {
1068 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1069 }
1070 if (reason != null) {
1071 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1072 }
1073 if (extraInfo != null) {
1074 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1075 }
1076 if (info.isFailover()) {
1077 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1078 info.setFailover(false);
1079 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001080
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001081 NetworkStateTracker newNet = null;
1082 if (mNetAttributes[info.getType()].isDefault()) {
1083 newNet = tryFailover(info.getType());
1084 if (newNet != null) {
1085 NetworkInfo switchTo = newNet.getNetworkInfo();
1086 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1087 } else {
1088 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1089 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001090 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001091
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001092 // do this before we broadcast the change
1093 handleConnectivityChange();
1094
Mike Lockwood0f79b542009-08-14 14:18:49 -04001095 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001096 /*
1097 * If the failover network is already connected, then immediately send
1098 * out a followup broadcast indicating successful failover
1099 */
1100 if (newNet != null && newNet.getNetworkInfo().isConnected()) {
1101 sendConnectedBroadcast(newNet.getNetworkInfo());
1102 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001103 }
1104
1105 private void sendStickyBroadcast(Intent intent) {
1106 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001107 if (!mSystemReady) {
1108 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001109 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001110 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1111 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001112 }
1113 }
1114
1115 void systemReady() {
1116 synchronized(this) {
1117 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001118 if (mInitialBroadcast != null) {
1119 mContext.sendStickyBroadcast(mInitialBroadcast);
1120 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001121 }
1122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 }
1124
1125 private void handleConnect(NetworkInfo info) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001126 int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127
1128 // snapshot isFailover, because sendConnectedBroadcast() resets it
1129 boolean isFailover = info.isFailover();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001130 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131
Robert Greenwalt42acef32009-08-12 16:08:25 -07001132 // if this is a default net and other default is running
1133 // kill the one not preferred
1134 if (mNetAttributes[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001135 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1136 if ((type != mNetworkPreference &&
1137 mNetAttributes[mActiveDefaultNetwork].mPriority >
1138 mNetAttributes[type].mPriority) ||
1139 mNetworkPreference == mActiveDefaultNetwork) {
1140 // don't accept this one
Joe Onorato8a9b2202010-02-26 18:56:32 -08001141 if (DBG) Slog.v(TAG, "Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001142 "to torn down network " + info.getTypeName());
1143 teardown(thisNet);
1144 return;
1145 } else {
1146 // tear down the other
1147 NetworkStateTracker otherNet =
1148 mNetTrackers[mActiveDefaultNetwork];
Joe Onorato8a9b2202010-02-26 18:56:32 -08001149 if (DBG) Slog.v(TAG, "Policy requires " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001150 otherNet.getNetworkInfo().getTypeName() +
1151 " teardown");
1152 if (!teardown(otherNet)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001153 Slog.e(TAG, "Network declined teardown request");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001154 return;
1155 }
1156 if (isFailover) {
1157 otherNet.releaseWakeLock();
1158 }
1159 }
1160 }
1161 mActiveDefaultNetwork = type;
1162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001164 updateNetworkSettings(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001165 handleConnectivityChange();
1166 sendConnectedBroadcast(info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 }
1168
1169 private void handleScanResultsAvailable(NetworkInfo info) {
1170 int networkType = info.getType();
1171 if (networkType != ConnectivityManager.TYPE_WIFI) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001172 if (DBG) Slog.v(TAG, "Got ScanResultsAvailable for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001173 info.getTypeName() + " network. Don't know how to handle.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 mNetTrackers[networkType].interpretScanResultsAvailable();
1177 }
1178
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001179 private void handleNotificationChange(boolean visible, int id,
1180 Notification notification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 NotificationManager notificationManager = (NotificationManager) mContext
1182 .getSystemService(Context.NOTIFICATION_SERVICE);
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 if (visible) {
1185 notificationManager.notify(id, notification);
1186 } else {
1187 notificationManager.cancel(id);
1188 }
1189 }
1190
1191 /**
1192 * After any kind of change in the connectivity state of any network,
1193 * make sure that anything that depends on the connectivity state of
1194 * more than one network is set up correctly. We're mainly concerned
1195 * with making sure that the list of DNS servers is set up according
1196 * to which networks are connected, and ensuring that the right routing
1197 * table entries exist.
1198 */
1199 private void handleConnectivityChange() {
1200 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001201 * If a non-default network is enabled, add the host routes that
Robert Greenwalt1ef95f92009-09-30 21:01:30 -07001202 * will allow it's DNS servers to be accessed. Only
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 * If both mobile and wifi are enabled, add the host routes that
1204 * will allow MMS traffic to pass on the mobile network. But
1205 * remove the default route for the mobile network, so that there
1206 * will be only one default route, to ensure that all traffic
1207 * except MMS will travel via Wi-Fi.
1208 */
Robert Greenwalt42acef32009-08-12 16:08:25 -07001209 handleDnsConfigurationChange();
1210
1211 for (int netType : mPriorityList) {
1212 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
1213 if (mNetAttributes[netType].isDefault()) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07001214 addDefaultRoute(mNetTrackers[netType]);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001215 } else {
Irfan Sheriffd649c122010-06-09 15:39:36 -07001216 addPrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001217 }
1218 } else {
1219 if (mNetAttributes[netType].isDefault()) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07001220 removeDefaultRoute(mNetTrackers[netType]);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001221 } else {
Irfan Sheriffd649c122010-06-09 15:39:36 -07001222 removePrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001223 }
1224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 }
1226 }
1227
Irfan Sheriffd649c122010-06-09 15:39:36 -07001228 private void addPrivateDnsRoutes(NetworkStateTracker nt) {
1229 String interfaceName = nt.getInterfaceName();
1230 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1231
1232 if (DBG) {
1233 Slog.d(TAG, "addPrivateDnsRoutes for " + nt +
1234 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1235 }
1236 String[] dnsList = getNameServerList(nt.getDnsPropNames());
1237 if (interfaceName != null && !privateDnsRouteSet) {
1238 for (String addrString : dnsList) {
1239 int addr = NetworkUtils.lookupHost(addrString);
1240 if (addr != -1 && addr != 0) {
1241 if (DBG) Slog.d(TAG, " adding "+addrString+" ("+addr+")");
1242 NetworkUtils.addHostRoute(interfaceName, addr);
1243 }
1244 }
1245 nt.privateDnsRouteSet(true);
1246 }
1247 }
1248
1249 private void removePrivateDnsRoutes(NetworkStateTracker nt) {
1250 // TODO - we should do this explicitly but the NetUtils api doesnt
1251 // support this yet - must remove all. No worse than before
1252 String interfaceName = nt.getInterfaceName();
1253 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1254 if (interfaceName != null && privateDnsRouteSet) {
1255 if (DBG) {
1256 Slog.d(TAG, "removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
1257 " (" + interfaceName + ")");
1258 }
1259 NetworkUtils.removeHostRoutes(interfaceName);
1260 nt.privateDnsRouteSet(false);
1261 }
1262 }
1263
1264 /**
1265 * Return the IP addresses of the DNS servers available for this
1266 * network interface.
1267 * @param propertyNames the names of the system properties whose values
1268 * give the IP addresses. Properties with no values are skipped.
1269 * @return an array of {@code String}s containing the IP addresses
1270 * of the DNS servers, in dot-notation. This may have fewer
1271 * non-null entries than the list of names passed in, since
1272 * some of the passed-in names may have empty values.
1273 */
1274 String[] getNameServerList(String[] propertyNames) {
1275 String[] dnsAddresses = new String[propertyNames.length];
1276 int i, j;
1277
1278 for (i = 0, j = 0; i < propertyNames.length; i++) {
1279 String value = SystemProperties.get(propertyNames[i]);
1280 // The GSM layer sometimes sets a bogus DNS server address of
1281 // 0.0.0.0
1282 if (!TextUtils.isEmpty(value) && !TextUtils.equals(value, "0.0.0.0")) {
1283 dnsAddresses[j++] = value;
1284 }
1285 }
1286 return dnsAddresses;
1287 }
1288
1289 private void addDefaultRoute(NetworkStateTracker nt) {
1290 String interfaceName = nt.getInterfaceName();
1291 int defaultGatewayAddr = nt.getDefaultGatewayAddr();
1292 boolean defaultRouteSet = nt.isDefaultRouteSet();
1293 NetworkInfo networkInfo = nt.getNetworkInfo();
1294
1295 if ((interfaceName != null) && (defaultGatewayAddr != 0) &&
1296 defaultRouteSet == false) {
1297 if (DBG) {
1298 Slog.d(TAG, "addDefaultRoute for " + networkInfo.getTypeName() +
1299 " (" + interfaceName + "), GatewayAddr=" + defaultGatewayAddr);
1300 }
1301 NetworkUtils.setDefaultRoute(interfaceName, defaultGatewayAddr);
1302 nt.defaultRouteSet(true);
1303 }
1304 }
1305
1306
1307 public void removeDefaultRoute(NetworkStateTracker nt) {
1308 String interfaceName = nt.getInterfaceName();
1309 boolean defaultRouteSet = nt.isDefaultRouteSet();
1310 NetworkInfo networkInfo = nt.getNetworkInfo();
1311
1312 if (interfaceName != null && defaultRouteSet == true) {
1313 if (DBG) {
1314 Slog.d(TAG, "removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1315 interfaceName + ")");
1316 }
1317 NetworkUtils.removeDefaultRoute(interfaceName);
1318 nt.defaultRouteSet(false);
1319 }
1320 }
1321
1322 /**
1323 * Reads the network specific TCP buffer sizes from SystemProperties
1324 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1325 * wide use
1326 */
1327 public void updateNetworkSettings(NetworkStateTracker nt) {
1328 String key = nt.getTcpBufferSizesPropName();
1329 String bufferSizes = SystemProperties.get(key);
1330
1331 if (bufferSizes.length() == 0) {
1332 Slog.e(TAG, key + " not found in system properties. Using defaults");
1333
1334 // Setting to default values so we won't be stuck to previous values
1335 key = "net.tcp.buffersize.default";
1336 bufferSizes = SystemProperties.get(key);
1337 }
1338
1339 // Set values in kernel
1340 if (bufferSizes.length() != 0) {
1341 if (DBG) {
1342 Slog.v(TAG, "Setting TCP values: [" + bufferSizes
1343 + "] which comes from [" + key + "]");
1344 }
1345 setBufferSize(bufferSizes);
1346 }
1347 }
1348
1349 /**
1350 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1351 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1352 *
1353 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1354 * writeMin, writeInitial, writeMax"
1355 */
1356 private void setBufferSize(String bufferSizes) {
1357 try {
1358 String[] values = bufferSizes.split(",");
1359
1360 if (values.length == 6) {
1361 final String prefix = "/sys/kernel/ipv4/tcp_";
1362 stringToFile(prefix + "rmem_min", values[0]);
1363 stringToFile(prefix + "rmem_def", values[1]);
1364 stringToFile(prefix + "rmem_max", values[2]);
1365 stringToFile(prefix + "wmem_min", values[3]);
1366 stringToFile(prefix + "wmem_def", values[4]);
1367 stringToFile(prefix + "wmem_max", values[5]);
1368 } else {
1369 Slog.e(TAG, "Invalid buffersize string: " + bufferSizes);
1370 }
1371 } catch (IOException e) {
1372 Slog.e(TAG, "Can't set tcp buffer sizes:" + e);
1373 }
1374 }
1375
1376 /**
1377 * Writes string to file. Basically same as "echo -n $string > $filename"
1378 *
1379 * @param filename
1380 * @param string
1381 * @throws IOException
1382 */
1383 private void stringToFile(String filename, String string) throws IOException {
1384 FileWriter out = new FileWriter(filename);
1385 try {
1386 out.write(string);
1387 } finally {
1388 out.close();
1389 }
1390 }
1391
1392
Robert Greenwalt42acef32009-08-12 16:08:25 -07001393 /**
1394 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1395 * on the highest priority active net which this process requested.
1396 * If there aren't any, clear it out
1397 */
1398 private void reassessPidDns(int myPid, boolean doBump)
1399 {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001400 if (DBG) Slog.d(TAG, "reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001401 for(int i : mPriorityList) {
1402 if (mNetAttributes[i].isDefault()) {
1403 continue;
1404 }
1405 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001406 if (nt.getNetworkInfo().isConnected() &&
1407 !nt.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001408 List pids = mNetRequestersPids[i];
1409 for (int j=0; j<pids.size(); j++) {
1410 Integer pid = (Integer)pids.get(j);
1411 if (pid.intValue() == myPid) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07001412 String[] dnsList = getNameServerList(nt.getDnsPropNames());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001413 writePidDns(dnsList, myPid);
1414 if (doBump) {
1415 bumpDns();
1416 }
1417 return;
1418 }
1419 }
1420 }
1421 }
1422 // nothing found - delete
1423 for (int i = 1; ; i++) {
1424 String prop = "net.dns" + i + "." + myPid;
1425 if (SystemProperties.get(prop).length() == 0) {
1426 if (doBump) {
1427 bumpDns();
1428 }
1429 return;
1430 }
1431 SystemProperties.set(prop, "");
1432 }
1433 }
1434
1435 private void writePidDns(String[] dnsList, int pid) {
1436 int j = 1;
1437 for (String dns : dnsList) {
1438 if (dns != null && !TextUtils.equals(dns, "0.0.0.0")) {
1439 SystemProperties.set("net.dns" + j++ + "." + pid, dns);
1440 }
1441 }
1442 }
1443
1444 private void bumpDns() {
1445 /*
1446 * Bump the property that tells the name resolver library to reread
1447 * the DNS server list from the properties.
1448 */
1449 String propVal = SystemProperties.get("net.dnschange");
1450 int n = 0;
1451 if (propVal.length() != 0) {
1452 try {
1453 n = Integer.parseInt(propVal);
1454 } catch (NumberFormatException e) {}
1455 }
1456 SystemProperties.set("net.dnschange", "" + (n+1));
1457 }
1458
1459 private void handleDnsConfigurationChange() {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001460 // add default net's dns entries
1461 for (int x = mPriorityList.length-1; x>= 0; x--) {
1462 int netType = mPriorityList[x];
1463 NetworkStateTracker nt = mNetTrackers[netType];
Robert Greenwalt42acef32009-08-12 16:08:25 -07001464 if (nt != null && nt.getNetworkInfo().isConnected() &&
1465 !nt.isTeardownRequested()) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07001466 String[] dnsList = getNameServerList(nt.getDnsPropNames());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001467 if (mNetAttributes[netType].isDefault()) {
1468 int j = 1;
1469 for (String dns : dnsList) {
1470 if (dns != null && !TextUtils.equals(dns, "0.0.0.0")) {
Robert Greenwalt1ef95f92009-09-30 21:01:30 -07001471 if (DBG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001472 Slog.d(TAG, "adding dns " + dns + " for " +
Robert Greenwalt1ef95f92009-09-30 21:01:30 -07001473 nt.getNetworkInfo().getTypeName());
1474 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001475 SystemProperties.set("net.dns" + j++, dns);
1476 }
1477 }
1478 for (int k=j ; k<mNumDnsEntries; k++) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001479 if (DBG) Slog.d(TAG, "erasing net.dns" + k);
Robert Greenwaltb06324a2009-08-25 14:00:10 -07001480 SystemProperties.set("net.dns" + k, "");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001481 }
1482 mNumDnsEntries = j;
1483 } else {
1484 // set per-pid dns for attached secondary nets
1485 List pids = mNetRequestersPids[netType];
1486 for (int y=0; y< pids.size(); y++) {
1487 Integer pid = (Integer)pids.get(y);
1488 writePidDns(dnsList, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
1490 }
1491 }
1492 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001493
1494 bumpDns();
1495 }
1496
1497 private int getRestoreDefaultNetworkDelay() {
1498 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1499 NETWORK_RESTORE_DELAY_PROP_NAME);
1500 if(restoreDefaultNetworkDelayStr != null &&
1501 restoreDefaultNetworkDelayStr.length() != 0) {
1502 try {
1503 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1504 } catch (NumberFormatException e) {
1505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001507 return RESTORE_DEFAULT_NETWORK_DELAY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 }
1509
1510 @Override
1511 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001512 if (mContext.checkCallingOrSelfPermission(
1513 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001515 pw.println("Permission Denial: can't dump ConnectivityService " +
1516 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1517 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 return;
1519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 pw.println();
1521 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08001522 if (nst != null) {
1523 if (nst.getNetworkInfo().isConnected()) {
1524 pw.println("Active network: " + nst.getNetworkInfo().
1525 getTypeName());
1526 }
1527 pw.println(nst.getNetworkInfo());
1528 pw.println(nst);
1529 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001532
1533 pw.println("Network Requester Pids:");
1534 for (int net : mPriorityList) {
1535 String pidString = net + ": ";
1536 for (Object pid : mNetRequestersPids[net]) {
1537 pidString = pidString + pid.toString() + ", ";
1538 }
1539 pw.println(pidString);
1540 }
1541 pw.println();
1542
1543 pw.println("FeatureUsers:");
1544 for (Object requester : mFeatureUsers) {
1545 pw.println(requester.toString());
1546 }
1547 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001548
1549 mTethering.dump(fd, pw, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
1551
Robert Greenwalt42acef32009-08-12 16:08:25 -07001552 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 private class MyHandler extends Handler {
1554 @Override
1555 public void handleMessage(Message msg) {
1556 NetworkInfo info;
1557 switch (msg.what) {
1558 case NetworkStateTracker.EVENT_STATE_CHANGED:
1559 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08001560 int type = info.getType();
1561 NetworkInfo.State state = info.getState();
Robert Greenwalt6e6dec22010-01-25 16:14:00 -08001562 // only do this optimization for wifi. It going into scan mode for location
1563 // services generates alot of noise. Meanwhile the mms apn won't send out
1564 // subsequent notifications when on default cellular because it never
1565 // disconnects.. so only do this to wifi notifications. Fixed better when the
1566 // APN notifications are standardized.
1567 if (mNetAttributes[type].mLastState == state &&
1568 mNetAttributes[type].mRadio == ConnectivityManager.TYPE_WIFI) {
Robert Greenwalt511288a2009-12-07 11:33:18 -08001569 if (DBG) {
Robert Greenwalt6e6dec22010-01-25 16:14:00 -08001570 // TODO - remove this after we validate the dropping doesn't break
1571 // anything
Joe Onorato8a9b2202010-02-26 18:56:32 -08001572 Slog.d(TAG, "Dropping ConnectivityChange for " +
Robert Greenwalt1193ae42010-01-13 09:36:31 -08001573 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08001574 state + "/" + info.getDetailedState());
1575 }
1576 return;
1577 }
1578 mNetAttributes[type].mLastState = state;
1579
Joe Onorato8a9b2202010-02-26 18:56:32 -08001580 if (DBG) Slog.d(TAG, "ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001581 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08001582 state + "/" + info.getDetailedState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583
1584 // Connectivity state changed:
1585 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001586 // [12-9] Network subtype (for mobile network, as defined
1587 // by TelephonyManager)
1588 // [8-3] Detailed state ordinal (as defined by
1589 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 // [2-0] Network type (as defined by ConnectivityManager)
1591 int eventLogParam = (info.getType() & 0x7) |
1592 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1593 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001594 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001595 eventLogParam);
1596
1597 if (info.getDetailedState() ==
1598 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08001600 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08001602 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001604 // the logic here is, handle SUSPENDED the same as
1605 // DISCONNECTED. The only difference being we are
1606 // broadcasting an intent with NetworkInfo that's
1607 // suspended. This allows the applications an
1608 // opportunity to handle DISCONNECTED and SUSPENDED
1609 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08001611 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 handleConnect(info);
1613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 break;
1615
1616 case NetworkStateTracker.EVENT_SCAN_RESULTS_AVAILABLE:
1617 info = (NetworkInfo) msg.obj;
1618 handleScanResultsAvailable(info);
1619 break;
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 case NetworkStateTracker.EVENT_NOTIFICATION_CHANGED:
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001622 handleNotificationChange(msg.arg1 == 1, msg.arg2,
1623 (Notification) msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624
1625 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt42acef32009-08-12 16:08:25 -07001626 handleDnsConfigurationChange();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 break;
1628
1629 case NetworkStateTracker.EVENT_ROAMING_CHANGED:
1630 // fill me in
1631 break;
1632
1633 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
1634 // fill me in
1635 break;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001636 case NetworkStateTracker.EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001637 FeatureUser u = (FeatureUser)msg.obj;
1638 u.expire();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001639 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
1641 }
1642 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001643
1644 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08001645 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001646 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08001647
1648 if (isTetheringSupported()) {
1649 return mTethering.tether(iface);
1650 } else {
1651 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1652 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001653 }
1654
1655 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08001656 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001657 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08001658
1659 if (isTetheringSupported()) {
1660 return mTethering.untether(iface);
1661 } else {
1662 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1663 }
1664 }
1665
1666 // javadoc from interface
1667 public int getLastTetherError(String iface) {
1668 enforceTetherAccessPermission();
1669
1670 if (isTetheringSupported()) {
1671 return mTethering.getLastTetherError(iface);
1672 } else {
1673 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1674 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001675 }
1676
1677 // TODO - proper iface API for selection by property, inspection, etc
1678 public String[] getTetherableUsbRegexs() {
1679 enforceTetherAccessPermission();
1680 if (isTetheringSupported()) {
1681 return mTethering.getTetherableUsbRegexs();
1682 } else {
1683 return new String[0];
1684 }
1685 }
1686
1687 public String[] getTetherableWifiRegexs() {
1688 enforceTetherAccessPermission();
1689 if (isTetheringSupported()) {
1690 return mTethering.getTetherableWifiRegexs();
1691 } else {
1692 return new String[0];
1693 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001694 }
1695
1696 // TODO - move iface listing, queries, etc to new module
1697 // javadoc from interface
1698 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001699 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001700 return mTethering.getTetherableIfaces();
1701 }
1702
1703 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001704 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001705 return mTethering.getTetheredIfaces();
1706 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001707
Robert Greenwalt5a735062010-03-02 17:25:02 -08001708 public String[] getTetheringErroredIfaces() {
1709 enforceTetherAccessPermission();
1710 return mTethering.getErroredIfaces();
1711 }
1712
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001713 // if ro.tether.denied = true we default to no tethering
1714 // gservices could set the secure setting to 1 though to enable it on a build where it
1715 // had previously been turned off.
1716 public boolean isTetheringSupported() {
1717 enforceTetherAccessPermission();
1718 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08001719 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
1720 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
1721 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723}