blob: dd76eb8c705cc53efcd62302e01faef5351f6a99 [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
Jeff Sharkey921ebf22011-05-19 17:12:49 -070019import static android.Manifest.permission.UPDATE_DEVICE_STATS;
20import static android.net.ConnectivityManager.isNetworkTypeValid;
21import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
22import static android.net.NetworkPolicyManager.RULE_REJECT_PAID;
23
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080024import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080025import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070029import android.database.ContentObserver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080030import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080031import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080032import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080033import android.net.IConnectivityManager;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070034import android.net.INetworkPolicyListener;
35import android.net.INetworkPolicyManager;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080036import android.net.LinkProperties;
The Android Open Source Project28527d22009-03-03 19:31:44 -080037import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070038import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080039import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070040import android.net.NetworkInfo.DetailedState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080041import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070042import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070043import android.net.Proxy;
44import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070045import android.net.RouteInfo;
Hung-ying Tyan4e723422011-01-19 16:48:38 +080046import android.net.vpn.VpnManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -080047import android.net.wifi.WifiStateTracker;
48import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040049import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080050import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070051import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070052import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070053import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080054import android.os.Looper;
55import android.os.Message;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070056import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070057import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080058import android.os.ServiceManager;
59import android.os.SystemProperties;
60import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070061import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080062import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080063import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070064import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080065
Robert Greenwalt2034b912009-08-12 16:08:25 -070066import com.android.internal.telephony.Phone;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080067import com.android.server.connectivity.Tethering;
68
The Android Open Source Project28527d22009-03-03 19:31:44 -080069import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070070import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080071import java.io.PrintWriter;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070072import java.net.InetAddress;
73import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -070074import java.util.ArrayList;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070075import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -070076import java.util.GregorianCalendar;
Robert Greenwalt2034b912009-08-12 16:08:25 -070077import java.util.List;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070078import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project28527d22009-03-03 19:31:44 -080079
80/**
81 * @hide
82 */
83public class ConnectivityService extends IConnectivityManager.Stub {
84
Robert Greenwalt063dc7d2010-10-05 19:12:26 -070085 private static final boolean DBG = true;
The Android Open Source Project28527d22009-03-03 19:31:44 -080086 private static final String TAG = "ConnectivityService";
87
Jeff Sharkey921ebf22011-05-19 17:12:49 -070088 private static final boolean LOGD_RULES = false;
89
Robert Greenwalt2034b912009-08-12 16:08:25 -070090 // how long to wait before switching back to a radio's default network
91 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
92 // system property that can override the above value
93 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
94 "android.telephony.apn-restore";
95
Robert Greenwaltbd492212011-05-06 17:10:53 -070096 // used in recursive route setting to add gateways for the host for which
97 // a host route was requested.
98 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
99
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800100 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800101 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800102
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700103 /** Currently active network rules by UID. */
104 private SparseIntArray mUidRules = new SparseIntArray();
105
The Android Open Source Project28527d22009-03-03 19:31:44 -0800106 /**
107 * Sometimes we want to refer to the individual network state
108 * trackers separately, and sometimes we just want to treat them
109 * abstractly.
110 */
111 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700112
113 /**
114 * A per Net list of the PID's that requested access to the net
115 * used both as a refcount and for per-PID DNS selection
116 */
117 private List mNetRequestersPids[];
118
Irfan Sheriff653e2a22010-06-07 09:03:04 -0700119 private WifiWatchdogService mWifiWatchdogService;
120
Robert Greenwalt2034b912009-08-12 16:08:25 -0700121 // priority order of the nettrackers
122 // (excluding dynamically set mNetworkPreference)
123 // TODO - move mNetworkTypePreference into this
124 private int[] mPriorityList;
125
The Android Open Source Project28527d22009-03-03 19:31:44 -0800126 private Context mContext;
127 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700128 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700129 // 0 is full bad, 100 is full good
130 private int mDefaultInetCondition = 0;
131 private int mDefaultInetConditionPublished = 0;
132 private boolean mInetConditionChangeInFlight = false;
133 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800134
135 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800136
137 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700138 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800139
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800140 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
141
Robert Greenwalt355205c2011-05-10 15:05:02 -0700142 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700143 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700144
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700145 private static final int ENABLED = 1;
146 private static final int DISABLED = 0;
147
148 // Share the event space with NetworkStateTracker (which can't see this
149 // internal class but sends us events). If you change these, change
150 // NetworkStateTracker.java too.
151 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
152 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
153
154 /**
155 * used internally as a delayed event to make us switch back to the
156 * default network
157 */
158 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
159 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
160
161 /**
162 * used internally to change our mobile data enabled flag
163 */
164 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
165 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
166
167 /**
168 * used internally to change our network preference setting
169 * arg1 = networkType to prefer
170 */
171 private static final int EVENT_SET_NETWORK_PREFERENCE =
172 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
173
174 /**
175 * used internally to synchronize inet condition reports
176 * arg1 = networkType
177 * arg2 = condition (0 bad, 100 good)
178 */
179 private static final int EVENT_INET_CONDITION_CHANGE =
180 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
181
182 /**
183 * used internally to mark the end of inet condition hold periods
184 * arg1 = networkType
185 */
186 private static final int EVENT_INET_CONDITION_HOLD_END =
187 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
188
189 /**
190 * used internally to set the background data preference
191 * arg1 = TRUE for enabled, FALSE for disabled
192 */
193 private static final int EVENT_SET_BACKGROUND_DATA =
194 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
195
196 /**
197 * used internally to set enable/disable cellular data
198 * arg1 = ENBALED or DISABLED
199 */
200 private static final int EVENT_SET_MOBILE_DATA =
201 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
202
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700203 /**
204 * used internally to clear a wakelock when transitioning
205 * from one net to another
206 */
207 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
208 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
209
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700210 /**
211 * used internally to reload global proxy settings
212 */
213 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
214 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
215
Robert Greenwalt34848c02011-03-25 13:09:25 -0700216 /**
217 * used internally to set external dependency met/unmet
218 * arg1 = ENABLED (met) or DISABLED (unmet)
219 * arg2 = NetworkType
220 */
221 private static final int EVENT_SET_DEPENDENCY_MET =
222 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
223
Robert Greenwalt2034b912009-08-12 16:08:25 -0700224 private Handler mHandler;
225
226 // list of DeathRecipients used to make sure features are turned off when
227 // a process dies
228 private List mFeatureUsers;
229
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400230 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800231 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400232
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700233 private PowerManager.WakeLock mNetTransitionWakeLock;
234 private String mNetTransitionWakeLockCausedBy = "";
235 private int mNetTransitionWakeLockSerialNumber;
236 private int mNetTransitionWakeLockTimeout;
237
Robert Greenwalt94daa182010-09-01 11:34:05 -0700238 private InetAddress mDefaultDns;
239
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700240 // used in DBG mode to track inet condition reports
241 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
242 private ArrayList mInetLog;
243
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700244 // track the current default http proxy - tell the world if we get a new one (real change)
245 private ProxyProperties mDefaultProxy = null;
246 // track the global proxy.
247 private ProxyProperties mGlobalProxy = null;
248 private final Object mGlobalProxyLock = new Object();
249
250 private SettingsObserver mSettingsObserver;
251
Robert Greenwalt34848c02011-03-25 13:09:25 -0700252 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700253 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700254
Robert Greenwalt12c44552009-12-07 11:33:18 -0800255 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700256 public int mSimultaneity;
257 public int mType;
258 public RadioAttributes(String init) {
259 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700260 mType = Integer.parseInt(fragments[0]);
261 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700262 }
263 }
264 RadioAttributes[] mRadioAttributes;
265
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700266 public ConnectivityService(
267 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800268 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800269
Wink Saville775aad62010-09-02 19:23:52 -0700270 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
271 handlerThread.start();
272 mHandler = new MyHandler(handlerThread.getLooper());
273
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800274 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
275 Settings.Secure.BACKGROUND_DATA, 1) == 1);
276
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800277 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800278 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
279 String id = Settings.Secure.getString(context.getContentResolver(),
280 Settings.Secure.ANDROID_ID);
281 if (id != null && id.length() > 0) {
282 String name = new String("android_").concat(id);
283 SystemProperties.set("net.hostname", name);
284 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800285 }
286
Robert Greenwalt94daa182010-09-01 11:34:05 -0700287 // read our default dns server ip
288 String dns = Settings.Secure.getString(context.getContentResolver(),
289 Settings.Secure.DEFAULT_DNS_SERVER);
290 if (dns == null || dns.length() == 0) {
291 dns = context.getResources().getString(
292 com.android.internal.R.string.config_default_dns_server);
293 }
294 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800295 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
296 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800297 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700298 }
299
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700300 mContext = checkNotNull(context, "missing Context");
301 mNetd = checkNotNull(netd, "missing INetworkManagementService");
302 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700303
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700304 try {
305 mPolicyManager.registerListener(mPolicyListener);
306 } catch (RemoteException e) {
307 // ouch, no rules updates means some processes may never get network
308 Slog.e(TAG, "unable to register INetworkPolicyListener", e);
309 }
310
311 final PowerManager powerManager = (PowerManager) context.getSystemService(
312 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700313 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
314 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
315 com.android.internal.R.integer.config_networkTransitionTimeout);
316
Robert Greenwalt2034b912009-08-12 16:08:25 -0700317 mNetTrackers = new NetworkStateTracker[
318 ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700319
The Android Open Source Project28527d22009-03-03 19:31:44 -0800320 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700321
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700322 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700323 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700324
Robert Greenwalt2034b912009-08-12 16:08:25 -0700325 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700326 String[] raStrings = context.getResources().getStringArray(
327 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700328 for (String raString : raStrings) {
329 RadioAttributes r = new RadioAttributes(raString);
330 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800331 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700332 continue;
333 }
334 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800335 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700336 r.mType);
337 continue;
338 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700339 mRadioAttributes[r.mType] = r;
340 }
341
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700342 String[] naStrings = context.getResources().getStringArray(
343 com.android.internal.R.array.networkAttributes);
344 for (String naString : naStrings) {
345 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700346 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700347 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800348 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700349 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700350 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700351 }
Wink Savillef2a62832011-04-07 14:23:45 -0700352 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800353 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700354 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700355 continue;
356 }
Wink Savillef2a62832011-04-07 14:23:45 -0700357 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800358 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700359 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700360 continue;
361 }
Wink Savillef2a62832011-04-07 14:23:45 -0700362 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700363 mNetworksDefined++;
364 } catch(Exception e) {
365 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700366 }
367 }
368
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700369 // high priority first
370 mPriorityList = new int[mNetworksDefined];
371 {
372 int insertionPoint = mNetworksDefined-1;
373 int currentLowest = 0;
374 int nextLowest = 0;
375 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700376 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700377 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700378 if (na.priority < currentLowest) continue;
379 if (na.priority > currentLowest) {
380 if (na.priority < nextLowest || nextLowest == 0) {
381 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700382 }
383 continue;
384 }
Wink Savillef2a62832011-04-07 14:23:45 -0700385 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700386 }
387 currentLowest = nextLowest;
388 nextLowest = 0;
389 }
390 }
391
392 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
393 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700394 mNetRequestersPids[i] = new ArrayList();
395 }
396
397 mFeatureUsers = new ArrayList();
398
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700399 mNumDnsEntries = 0;
400
401 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
402 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800403 /*
404 * Create the network state trackers for Wi-Fi and mobile
405 * data. Maybe this could be done with a factory class,
406 * but it's not clear that it's worth it, given that
407 * the number of different network types is not going
408 * to change very often.
409 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700410 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700411 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700412 case ConnectivityManager.TYPE_WIFI:
Wink Savillee70c6f52010-12-03 12:01:38 -0800413 if (DBG) log("Starting Wifi Service.");
Wink Saville7fabfa22010-08-13 16:11:42 -0700414 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff25be0762010-07-28 09:35:20 -0700415 WifiService wifiService = new WifiService(context);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700416 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff25be0762010-07-28 09:35:20 -0700417 wifiService.checkAndStartWifi();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700418 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Saville7fabfa22010-08-13 16:11:42 -0700419 wst.startMonitoring(context, mHandler);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800420
Irfan Sheriff653e2a22010-06-07 09:03:04 -0700421 //TODO: as part of WWS refactor, create only when needed
Irfan Sheriff25be0762010-07-28 09:35:20 -0700422 mWifiWatchdogService = new WifiWatchdogService(context);
Irfan Sheriff653e2a22010-06-07 09:03:04 -0700423
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700424 break;
425 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700426 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700427 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700428 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700429 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800430 case ConnectivityManager.TYPE_DUMMY:
431 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700432 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800433 mNetTrackers[netType].startMonitoring(context, mHandler);
434 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800435 case ConnectivityManager.TYPE_BLUETOOTH:
436 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
437 mNetTrackers[netType].startMonitoring(context, mHandler);
438 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800439 case ConnectivityManager.TYPE_ETHERNET:
440 mNetTrackers[netType] = EthernetDataTracker.getInstance();
441 mNetTrackers[netType].startMonitoring(context, mHandler);
442 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700443 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800444 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700445 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700446 continue;
447 }
448 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800449
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700450 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
451 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
452
453 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800454 mTetheringConfigValid = (((mNetTrackers[ConnectivityManager.TYPE_MOBILE_DUN] != null) ||
455 !mTethering.isDunRequired()) &&
456 (mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700457 mTethering.getTetherableWifiRegexs().length != 0 ||
458 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800459 mTethering.getUpstreamIfaceRegexs().length != 0);
460
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700461 if (DBG) {
462 mInetLog = new ArrayList();
463 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700464
465 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
466 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800467
468 loadGlobalProxy();
Hung-ying Tyan4e723422011-01-19 16:48:38 +0800469
470 VpnManager.startVpnService(context);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800471 }
472
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700473
The Android Open Source Project28527d22009-03-03 19:31:44 -0800474 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700475 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800476 * @param preference the new preference
477 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700478 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800479 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700480
481 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800482 }
483
484 public int getNetworkPreference() {
485 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700486 int preference;
487 synchronized(this) {
488 preference = mNetworkPreference;
489 }
490 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800491 }
492
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700493 private void handleSetNetworkPreference(int preference) {
494 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700495 mNetConfigs[preference] != null &&
496 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700497 if (mNetworkPreference != preference) {
498 final ContentResolver cr = mContext.getContentResolver();
499 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
500 synchronized(this) {
501 mNetworkPreference = preference;
502 }
503 enforcePreference();
504 }
505 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800506 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700507
The Android Open Source Project28527d22009-03-03 19:31:44 -0800508 private int getPersistedNetworkPreference() {
509 final ContentResolver cr = mContext.getContentResolver();
510
511 final int networkPrefSetting = Settings.Secure
512 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
513 if (networkPrefSetting != -1) {
514 return networkPrefSetting;
515 }
516
517 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
518 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700519
The Android Open Source Project28527d22009-03-03 19:31:44 -0800520 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700521 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800522 * In this method, we only tear down a non-preferred network. Establishing
523 * a connection to the preferred network is taken care of when we handle
524 * the disconnect event from the non-preferred network
525 * (see {@link #handleDisconnect(NetworkInfo)}).
526 */
527 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700528 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800529 return;
530
Robert Greenwalt2034b912009-08-12 16:08:25 -0700531 if (!mNetTrackers[mNetworkPreference].isAvailable())
532 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800533
Robert Greenwalt2034b912009-08-12 16:08:25 -0700534 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700535 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700536 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700537 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800538 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700539 " in enforcePreference");
540 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700541 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800542 }
543 }
544 }
545
546 private boolean teardown(NetworkStateTracker netTracker) {
547 if (netTracker.teardown()) {
548 netTracker.setTeardownRequested(true);
549 return true;
550 } else {
551 return false;
552 }
553 }
554
555 /**
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700556 * Check if UID is blocked from using the given {@link NetworkInfo}.
557 */
558 private boolean isNetworkBlocked(NetworkInfo info, int uid) {
559 synchronized (mUidRules) {
560 return isNetworkBlockedLocked(info, uid);
561 }
562 }
563
564 /**
565 * Check if UID is blocked from using the given {@link NetworkInfo}.
566 */
567 private boolean isNetworkBlockedLocked(NetworkInfo info, int uid) {
568 // TODO: expand definition of "paid" network to cover tethered or paid
569 // hotspot use cases.
570 final boolean networkIsPaid = info.getType() != ConnectivityManager.TYPE_WIFI;
571 final int uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
572
573 if (networkIsPaid && (uidRules & RULE_REJECT_PAID) != 0) {
574 return true;
575 }
576
577 // no restrictive rules; network is visible
578 return false;
579 }
580
581 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800582 * Return NetworkInfo for the active (i.e., connected) network interface.
583 * It is assumed that at most one network is active at a time. If more
584 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700585 * @return the info for the active network, or {@code null} if none is
586 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800587 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700588 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800589 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700590 enforceAccessPermission();
591 final int uid = Binder.getCallingUid();
592 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800593 }
594
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700595 @Override
596 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
597 enforceConnectivityInternalPermission();
598 return getNetworkInfo(mActiveDefaultNetwork, uid);
599 }
600
601 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800602 public NetworkInfo getNetworkInfo(int networkType) {
603 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700604 final int uid = Binder.getCallingUid();
605 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800606 }
607
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700608 private NetworkInfo getNetworkInfo(int networkType, int uid) {
609 NetworkInfo info = null;
610 if (isNetworkTypeValid(networkType)) {
611 final NetworkStateTracker tracker = mNetTrackers[networkType];
612 if (tracker != null) {
613 info = tracker.getNetworkInfo();
614 if (isNetworkBlocked(info, uid)) {
615 // network is blocked; clone and override state
616 info = new NetworkInfo(info);
617 info.setDetailedState(DetailedState.BLOCKED, null, null);
618 }
619 }
620 }
621 return info;
622 }
623
624 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800625 public NetworkInfo[] getAllNetworkInfo() {
626 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700627 final int uid = Binder.getCallingUid();
628 final NetworkInfo[] result = new NetworkInfo[mNetworksDefined];
The Android Open Source Project28527d22009-03-03 19:31:44 -0800629 int i = 0;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700630 synchronized (mUidRules) {
631 for (NetworkStateTracker tracker : mNetTrackers) {
632 if (tracker != null) {
633 NetworkInfo info = tracker.getNetworkInfo();
634 if (isNetworkBlockedLocked(info, uid)) {
635 // network is blocked; clone and override state
636 info = new NetworkInfo(info);
637 info.setDetailedState(DetailedState.BLOCKED, null, null);
638 }
639 result[i++] = info;
640 }
641 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800642 }
643 return result;
644 }
645
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700646 /**
647 * Return LinkProperties for the active (i.e., connected) default
648 * network interface. It is assumed that at most one default network
649 * is active at a time. If more than one is active, it is indeterminate
650 * which will be returned.
651 * @return the ip properties for the active network, or {@code null} if
652 * none is active
653 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700654 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700655 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700656 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700657 }
658
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700659 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700660 public LinkProperties getLinkProperties(int networkType) {
661 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700662 if (isNetworkTypeValid(networkType)) {
663 final NetworkStateTracker tracker = mNetTrackers[networkType];
664 if (tracker != null) {
665 return tracker.getLinkProperties();
666 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700667 }
668 return null;
669 }
670
The Android Open Source Project28527d22009-03-03 19:31:44 -0800671 public boolean setRadios(boolean turnOn) {
672 boolean result = true;
673 enforceChangePermission();
674 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700675 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800676 }
677 return result;
678 }
679
680 public boolean setRadio(int netType, boolean turnOn) {
681 enforceChangePermission();
682 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
683 return false;
684 }
685 NetworkStateTracker tracker = mNetTrackers[netType];
686 return tracker != null && tracker.setRadio(turnOn);
687 }
688
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700689 /**
690 * Used to notice when the calling process dies so we can self-expire
691 *
692 * Also used to know if the process has cleaned up after itself when
693 * our auto-expire timer goes off. The timer has a link to an object.
694 *
695 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700696 private class FeatureUser implements IBinder.DeathRecipient {
697 int mNetworkType;
698 String mFeature;
699 IBinder mBinder;
700 int mPid;
701 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800702 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700703
704 FeatureUser(int type, String feature, IBinder binder) {
705 super();
706 mNetworkType = type;
707 mFeature = feature;
708 mBinder = binder;
709 mPid = getCallingPid();
710 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800711 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700712
Robert Greenwalt2034b912009-08-12 16:08:25 -0700713 try {
714 mBinder.linkToDeath(this, 0);
715 } catch (RemoteException e) {
716 binderDied();
717 }
718 }
719
720 void unlinkDeathRecipient() {
721 mBinder.unlinkToDeath(this, 0);
722 }
723
724 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800725 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800726 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
727 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700728 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700729 }
730
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700731 public void expire() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800732 log("ConnectivityService FeatureUser expire(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800733 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
734 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700735 stopUsingNetworkFeature(this, false);
736 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800737
738 public String toString() {
739 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
740 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
741 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700742 }
743
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700744 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700745 public int startUsingNetworkFeature(int networkType, String feature,
746 IBinder binder) {
747 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800748 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700749 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800750 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700751 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700752 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700753 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800754 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700755
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700756 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700757
758 // TODO - move this into the MobileDataStateTracker
759 int usedNetworkType = networkType;
760 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800761 usedNetworkType = convertFeatureToNetworkType(feature);
762 if (usedNetworkType < 0) {
763 Slog.e(TAG, "Can't match any netTracker!");
764 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700765 }
766 }
767 NetworkStateTracker network = mNetTrackers[usedNetworkType];
768 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800769 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700770 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700771 NetworkStateTracker radio = mNetTrackers[networkType];
772 NetworkInfo ni = network.getNetworkInfo();
773
774 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800775 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800776 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
777 return Phone.APN_TYPE_NOT_AVAILABLE;
778 } else {
779 // else make the attempt anyway - probably giving REQUEST_STARTED below
780 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700781 }
782
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700783 synchronized(this) {
784 mFeatureUsers.add(f);
785 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
786 // this gets used for per-pid dns when connected
787 mNetRequestersPids[usedNetworkType].add(currentPid);
788 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700789 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700790
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700791 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
792
793 if (restoreTimer >= 0) {
794 mHandler.sendMessageDelayed(
795 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
796 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700797
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700798 if ((ni.isConnectedOrConnecting() == true) &&
799 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700800 if (ni.isConnected() == true) {
801 // add the pid-specific dns
Robert Greenwalt3afbead2010-07-23 15:46:26 -0700802 handleDnsConfigurationChange(networkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800803 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700804 return Phone.APN_ALREADY_ACTIVE;
805 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800806 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700807 return Phone.APN_REQUEST_STARTED;
808 }
809
810 // check if the radio in play can make another contact
811 // assume if cannot for now
812
Wink Savillee70c6f52010-12-03 12:01:38 -0800813 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700814 network.reconnect();
815 return Phone.APN_REQUEST_STARTED;
816 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800817 // need to remember this unsupported request so we respond appropriately on stop
818 synchronized(this) {
819 mFeatureUsers.add(f);
820 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
821 // this gets used for per-pid dns when connected
822 mNetRequestersPids[usedNetworkType].add(currentPid);
823 }
824 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700825 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700826 }
827 }
828 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800829 }
830
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700831 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800832 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700833 enforceChangePermission();
834
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700835 int pid = getCallingPid();
836 int uid = getCallingUid();
837
838 FeatureUser u = null;
839 boolean found = false;
840
841 synchronized(this) {
842 for (int i = 0; i < mFeatureUsers.size() ; i++) {
843 u = (FeatureUser)mFeatureUsers.get(i);
844 if (uid == u.mUid && pid == u.mPid &&
845 networkType == u.mNetworkType &&
846 TextUtils.equals(feature, u.mFeature)) {
847 found = true;
848 break;
849 }
850 }
851 }
852 if (found && u != null) {
853 // stop regardless of how many other time this proc had called start
854 return stopUsingNetworkFeature(u, true);
855 } else {
856 // none found!
Wink Savillee70c6f52010-12-03 12:01:38 -0800857 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700858 return 1;
859 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700860 }
861
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700862 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
863 int networkType = u.mNetworkType;
864 String feature = u.mFeature;
865 int pid = u.mPid;
866 int uid = u.mUid;
867
868 NetworkStateTracker tracker = null;
869 boolean callTeardown = false; // used to carry our decision outside of sync block
870
Robert Greenwalt2034b912009-08-12 16:08:25 -0700871 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800872 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700873 ": " + feature);
874 }
Robert Greenwalt28f43012009-10-06 17:52:40 -0700875
The Android Open Source Project28527d22009-03-03 19:31:44 -0800876 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
877 return -1;
878 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700879
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700880 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
881 // sync block
882 synchronized(this) {
883 // check if this process still has an outstanding start request
884 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800885 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700886 return 1;
887 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700888 u.unlinkDeathRecipient();
889 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
890 // If we care about duplicate requests, check for that here.
891 //
892 // This is done to support the extension of a request - the app
893 // can request we start the network feature again and renew the
894 // auto-shutoff delay. Normal "stop" calls from the app though
895 // do not pay attention to duplicate requests - in effect the
896 // API does not refcount and a single stop will counter multiple starts.
897 if (ignoreDups == false) {
898 for (int i = 0; i < mFeatureUsers.size() ; i++) {
899 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
900 if (x.mUid == u.mUid && x.mPid == u.mPid &&
901 x.mNetworkType == u.mNetworkType &&
902 TextUtils.equals(x.mFeature, u.mFeature)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800903 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700904 return 1;
905 }
906 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700907 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700908
909 // TODO - move to MobileDataStateTracker
910 int usedNetworkType = networkType;
911 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800912 usedNetworkType = convertFeatureToNetworkType(feature);
913 if (usedNetworkType < 0) {
914 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700915 }
916 }
917 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700918 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800919 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700920 return -1;
921 }
922 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700923 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700924 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -0800925 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700926 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800927 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700928 "others still using it");
929 return 1;
930 }
931 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -0800932 } else {
933 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700934 }
935 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800936 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700937 if (callTeardown) {
938 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700939 return 1;
940 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -0700941 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700942 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800943 }
944
945 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700946 * @deprecated use requestRouteToHostAddress instead
947 *
The Android Open Source Project28527d22009-03-03 19:31:44 -0800948 * Ensure that a network route exists to deliver traffic to the specified
949 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700950 * @param networkType the type of the network over which traffic to the
951 * specified host is to be routed
952 * @param hostAddress the IP address of the host to which the route is
953 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -0800954 * @return {@code true} on success, {@code false} on failure
955 */
956 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700957 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
958
959 if (inetAddress == null) {
960 return false;
961 }
962
963 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
964 }
965
966 /**
967 * Ensure that a network route exists to deliver traffic to the specified
968 * host via the specified network interface.
969 * @param networkType the type of the network over which traffic to the
970 * specified host is to be routed
971 * @param hostAddress the IP address of the host to which the route is
972 * desired
973 * @return {@code true} on success, {@code false} on failure
974 */
975 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800976 enforceChangePermission();
977 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
978 return false;
979 }
980 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -0700981
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700982 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
983 tracker.isTeardownRequested()) {
Robert Greenwalt4666ed02009-09-10 15:06:20 -0700984 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800985 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700986 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -0700987 }
988 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800989 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700990 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700991 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwaltbd492212011-05-06 17:10:53 -0700992 return addHostRoute(tracker, addr, 0);
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700993 } catch (UnknownHostException e) {}
994 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700995 }
996
997 /**
998 * Ensure that a network route exists to deliver traffic to the specified
999 * host via the mobile data network.
1000 * @param hostAddress the IP address of the host to which the route is desired,
1001 * in network byte order.
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001002 * TODO - deprecate
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001003 * @return {@code true} on success, {@code false} on failure
1004 */
Robert Greenwaltbd492212011-05-06 17:10:53 -07001005 private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress, int cycleCount) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001006 LinkProperties lp = nt.getLinkProperties();
1007 if ((lp == null) || (hostAddress == null)) return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001008
Robert Greenwaltbd492212011-05-06 17:10:53 -07001009 String interfaceName = lp.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001010 if (DBG) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001011 log("Requested host route to " + hostAddress + "(" + interfaceName + "), cycleCount=" +
1012 cycleCount);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001013 }
Robert Greenwaltbd492212011-05-06 17:10:53 -07001014 if (interfaceName == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001015 if (DBG) loge("addHostRoute failed due to null interface name");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001016 return false;
1017 }
Robert Greenwaltbd492212011-05-06 17:10:53 -07001018
1019 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), hostAddress);
Robert Greenwalt355205c2011-05-10 15:05:02 -07001020 InetAddress gatewayAddress = null;
Robert Greenwaltbd492212011-05-06 17:10:53 -07001021 if (bestRoute != null) {
Robert Greenwalt355205c2011-05-10 15:05:02 -07001022 gatewayAddress = bestRoute.getGateway();
Robert Greenwaltbd492212011-05-06 17:10:53 -07001023 // if the best route is ourself, don't relf-reference, just add the host route
Robert Greenwalt355205c2011-05-10 15:05:02 -07001024 if (hostAddress.equals(gatewayAddress)) gatewayAddress = null;
Robert Greenwaltbd492212011-05-06 17:10:53 -07001025 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001026 if (gatewayAddress != null) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001027 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1028 loge("Error adding hostroute - too much recursion");
1029 return false;
1030 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001031 if (!addHostRoute(nt, gatewayAddress, cycleCount+1)) return false;
Robert Greenwaltbd492212011-05-06 17:10:53 -07001032 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001033
1034 RouteInfo route = RouteInfo.makeHostRoute(hostAddress, gatewayAddress);
1035
1036 try {
1037 mNetd.addRoute(interfaceName, route);
1038 return true;
1039 } catch (Exception ex) {
1040 return false;
1041 }
Robert Greenwaltbd492212011-05-06 17:10:53 -07001042 }
1043
1044 // TODO support the removal of single host routes. Keep a ref count of them so we
1045 // aren't over-zealous
1046 private boolean removeHostRoute(NetworkStateTracker nt, InetAddress hostAddress) {
1047 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001048 }
1049
1050 /**
1051 * @see ConnectivityManager#getBackgroundDataSetting()
1052 */
1053 public boolean getBackgroundDataSetting() {
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001054 return mBackgroundDataEnabled.get();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001055 }
Robert Greenwalt0659da32009-07-16 17:21:39 -07001056
The Android Open Source Project28527d22009-03-03 19:31:44 -08001057 /**
1058 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1059 */
1060 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1061 mContext.enforceCallingOrSelfPermission(
1062 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1063 "ConnectivityService");
Robert Greenwalt0659da32009-07-16 17:21:39 -07001064
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001065 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1066
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001067 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1068 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1069 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001070
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001071 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwalt0ffdef12011-02-25 13:44:09 -08001072 Settings.Secure.putInt(mContext.getContentResolver(),
1073 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1074 Intent broadcast = new Intent(
1075 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1076 mContext.sendBroadcast(broadcast);
Robert Greenwalt0659da32009-07-16 17:21:39 -07001077 }
1078
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001079 /**
1080 * @see ConnectivityManager#getMobileDataEnabled()
1081 */
1082 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001083 // TODO: This detail should probably be in DataConnectionTracker's
1084 // which is where we store the value and maybe make this
1085 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001086 enforceAccessPermission();
1087 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1088 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savillee70c6f52010-12-03 12:01:38 -08001089 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001090 return retVal;
1091 }
1092
Robert Greenwalt34848c02011-03-25 13:09:25 -07001093 public void setDataDependency(int networkType, boolean met) {
1094 enforceChangePermission();
1095 if (DBG) {
1096 log("setDataDependency(" + networkType + ", " + met + ")");
1097 }
1098 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1099 (met ? ENABLED : DISABLED), networkType));
1100 }
1101
1102 private void handleSetDependencyMet(int networkType, boolean met) {
1103 if (mNetTrackers[networkType] != null) {
1104 if (DBG) {
1105 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1106 }
1107 mNetTrackers[networkType].setDependencyMet(met);
1108 }
1109 }
1110
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001111 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1112 @Override
1113 public void onRulesChanged(int uid, int uidRules) {
1114 // only someone like NPMS should only be calling us
1115 // TODO: create permission for modifying data policy
1116 mContext.enforceCallingOrSelfPermission(UPDATE_DEVICE_STATS, TAG);
1117
1118 if (LOGD_RULES) {
1119 Slog.d(TAG, "onRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1120 }
1121
1122 synchronized (mUidRules) {
1123 // skip update when we've already applied rules
1124 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1125 if (oldRules == uidRules) return;
1126
1127 mUidRules.put(uid, uidRules);
1128 }
1129
1130 // TODO: dispatch into NMS to push rules towards kernel module
1131 // TODO: notify UID when it has requested targeted updates
1132 }
1133 };
1134
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001135 /**
1136 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1137 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001138 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001139 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001140 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001141
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001142 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001143 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001144 }
1145
1146 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001147 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1148 if (DBG) {
1149 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001150 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001151 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001152 }
1153 }
1154
The Android Open Source Project28527d22009-03-03 19:31:44 -08001155 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001156 mContext.enforceCallingOrSelfPermission(
1157 android.Manifest.permission.ACCESS_NETWORK_STATE,
1158 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001159 }
1160
1161 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001162 mContext.enforceCallingOrSelfPermission(
1163 android.Manifest.permission.CHANGE_NETWORK_STATE,
1164 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001165 }
1166
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001167 // TODO Make this a special check when it goes public
1168 private void enforceTetherChangePermission() {
1169 mContext.enforceCallingOrSelfPermission(
1170 android.Manifest.permission.CHANGE_NETWORK_STATE,
1171 "ConnectivityService");
1172 }
1173
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001174 private void enforceTetherAccessPermission() {
1175 mContext.enforceCallingOrSelfPermission(
1176 android.Manifest.permission.ACCESS_NETWORK_STATE,
1177 "ConnectivityService");
1178 }
1179
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001180 private void enforceConnectivityInternalPermission() {
1181 mContext.enforceCallingOrSelfPermission(
1182 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1183 "ConnectivityService");
1184 }
1185
The Android Open Source Project28527d22009-03-03 19:31:44 -08001186 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001187 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1188 * network, we ignore it. If it is for the active network, we send out a
1189 * broadcast. But first, we check whether it might be possible to connect
1190 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001191 * @param info the {@code NetworkInfo} for the network
1192 */
1193 private void handleDisconnect(NetworkInfo info) {
1194
Robert Greenwalt2034b912009-08-12 16:08:25 -07001195 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001196
Robert Greenwalt2034b912009-08-12 16:08:25 -07001197 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001198 /*
1199 * If the disconnected network is not the active one, then don't report
1200 * this as a loss of connectivity. What probably happened is that we're
1201 * getting the disconnect for a network that we explicitly disabled
1202 * in accordance with network preference policies.
1203 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001204 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001205 List pids = mNetRequestersPids[prevNetType];
1206 for (int i = 0; i<pids.size(); i++) {
1207 Integer pid = (Integer)pids.get(i);
1208 // will remove them because the net's no longer connected
1209 // need to do this now as only now do we know the pids and
1210 // can properly null things that are no longer referenced.
1211 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001212 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001213 }
1214
The Android Open Source Project28527d22009-03-03 19:31:44 -08001215 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1216 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1217 if (info.isFailover()) {
1218 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1219 info.setFailover(false);
1220 }
1221 if (info.getReason() != null) {
1222 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1223 }
1224 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001225 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1226 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001227 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001228
Robert Greenwalt34848c02011-03-25 13:09:25 -07001229 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001230 tryFailover(prevNetType);
1231 if (mActiveDefaultNetwork != -1) {
1232 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001233 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1234 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001235 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001236 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1237 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001238 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001239 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001240 // do this before we broadcast the change
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001241 handleConnectivityChange(prevNetType);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001242
1243 sendStickyBroadcast(intent);
1244 /*
1245 * If the failover network is already connected, then immediately send
1246 * out a followup broadcast indicating successful failover
1247 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001248 if (mActiveDefaultNetwork != -1) {
1249 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001250 }
1251 }
1252
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001253 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001254 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001255 * If this is a default network, check if other defaults are available.
1256 * Try to reconnect on all available and let them hash it out when
1257 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001258 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001259 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001260 if (mActiveDefaultNetwork == prevNetType) {
1261 mActiveDefaultNetwork = -1;
1262 }
1263
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001264 // don't signal a reconnect for anything lower or equal priority than our
1265 // current connected default
1266 // TODO - don't filter by priority now - nice optimization but risky
1267// int currentPriority = -1;
1268// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001269// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001270// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001271 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001272 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001273 if (mNetConfigs[checkType] == null) continue;
1274 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001275
1276// Enabling the isAvailable() optimization caused mobile to not get
1277// selected if it was in the middle of error handling. Specifically
1278// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1279// would not be available and we wouldn't get connected to anything.
1280// So removing the isAvailable() optimization below for now. TODO: This
1281// optimization should work and we need to investigate why it doesn't work.
1282// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1283// complete before it is really complete.
1284// if (!mNetTrackers[checkType].isAvailable()) continue;
1285
Robert Greenwalt34848c02011-03-25 13:09:25 -07001286// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001287
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001288 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1289 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1290 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1291 checkInfo.setFailover(true);
1292 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001293 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001294 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001295 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001296 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001297 }
1298
1299 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001300 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1301 }
1302
1303 private void sendInetConditionBroadcast(NetworkInfo info) {
1304 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1305 }
1306
1307 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1308 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001309 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1310 if (info.isFailover()) {
1311 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1312 info.setFailover(false);
1313 }
1314 if (info.getReason() != null) {
1315 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1316 }
1317 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001318 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1319 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001320 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001321 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001322 sendStickyBroadcast(intent);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001323 }
1324
1325 /**
1326 * Called when an attempt to fail over to another network has failed.
1327 * @param info the {@link NetworkInfo} for the failed network
1328 */
1329 private void handleConnectionFailure(NetworkInfo info) {
1330 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001331
Robert Greenwalt2034b912009-08-12 16:08:25 -07001332 String reason = info.getReason();
1333 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001334
Robert Greenwalte981bc52010-10-08 16:35:52 -07001335 String reasonText;
1336 if (reason == null) {
1337 reasonText = ".";
1338 } else {
1339 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001340 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001341 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001342
1343 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1344 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1345 if (getActiveNetworkInfo() == null) {
1346 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1347 }
1348 if (reason != null) {
1349 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1350 }
1351 if (extraInfo != null) {
1352 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1353 }
1354 if (info.isFailover()) {
1355 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1356 info.setFailover(false);
1357 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001358
Robert Greenwalt34848c02011-03-25 13:09:25 -07001359 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001360 tryFailover(info.getType());
1361 if (mActiveDefaultNetwork != -1) {
1362 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001363 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1364 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001365 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001366 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1367 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001368 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001369
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001370 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001371 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001372 /*
1373 * If the failover network is already connected, then immediately send
1374 * out a followup broadcast indicating successful failover
1375 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001376 if (mActiveDefaultNetwork != -1) {
1377 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001378 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001379 }
1380
1381 private void sendStickyBroadcast(Intent intent) {
1382 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001383 if (!mSystemReady) {
1384 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001385 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001386 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1387 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001388 }
1389 }
1390
1391 void systemReady() {
1392 synchronized(this) {
1393 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001394 if (mInitialBroadcast != null) {
1395 mContext.sendStickyBroadcast(mInitialBroadcast);
1396 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001397 }
1398 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001399 // load the global proxy at startup
1400 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001401 }
1402
1403 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001404 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001405
1406 // snapshot isFailover, because sendConnectedBroadcast() resets it
1407 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001408 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001409
Robert Greenwalt2034b912009-08-12 16:08:25 -07001410 // if this is a default net and other default is running
1411 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001412 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001413 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1414 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001415 mNetConfigs[mActiveDefaultNetwork].priority >
1416 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001417 mNetworkPreference == mActiveDefaultNetwork) {
1418 // don't accept this one
Wink Savillee70c6f52010-12-03 12:01:38 -08001419 if (DBG) {
1420 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001421 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001422 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001423 teardown(thisNet);
1424 return;
1425 } else {
1426 // tear down the other
1427 NetworkStateTracker otherNet =
1428 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001429 if (DBG) {
1430 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001431 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001432 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001433 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001434 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001435 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001436 return;
1437 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001438 }
1439 }
1440 synchronized (ConnectivityService.this) {
1441 // have a new default network, release the transition wakelock in a second
1442 // if it's held. The second pause is to allow apps to reconnect over the
1443 // new network
1444 if (mNetTransitionWakeLock.isHeld()) {
1445 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001446 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001447 mNetTransitionWakeLockSerialNumber, 0),
1448 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001449 }
1450 }
1451 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001452 // this will cause us to come up initially as unconnected and switching
1453 // to connected after our normal pause unless somebody reports us as reall
1454 // disconnected
1455 mDefaultInetConditionPublished = 0;
1456 mDefaultConnectionSequence++;
1457 mInetConditionChangeInFlight = false;
1458 // Don't do this - if we never sign in stay, grey
1459 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001460 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001461 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001462 updateNetworkSettings(thisNet);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001463 handleConnectivityChange(type);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001464 sendConnectedBroadcast(info);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001465 }
1466
The Android Open Source Project28527d22009-03-03 19:31:44 -08001467 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001468 * After a change in the connectivity state of a network. We're mainly
1469 * concerned with making sure that the list of DNS servers is set up
1470 * according to which networks are connected, and ensuring that the
1471 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001472 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001473 private void handleConnectivityChange(int netType) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001474 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001475 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001476 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001477 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001478 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001479
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001480 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001481 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001482 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001483 addDefaultRoute(mNetTrackers[netType]);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001484 } else {
Robert Greenwalt1e2f2862011-04-01 10:51:22 -07001485 // many radios add a default route even when we don't want one.
1486 // remove the default route unless we need it for our active network
1487 if (mActiveDefaultNetwork != -1) {
1488 LinkProperties defaultLinkProperties =
1489 mNetTrackers[mActiveDefaultNetwork].getLinkProperties();
1490 LinkProperties newLinkProperties =
1491 mNetTrackers[netType].getLinkProperties();
1492 String defaultIface = defaultLinkProperties.getInterfaceName();
1493 if (defaultIface != null &&
1494 !defaultIface.equals(newLinkProperties.getInterfaceName())) {
1495 removeDefaultRoute(mNetTrackers[netType]);
1496 }
1497 }
Michael Jurka837e3642011-03-30 19:54:08 -07001498 addPrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001499 }
Kazuhiro Ondo3a340412011-04-30 20:10:57 -05001500
1501 /** Notify TetheringService if interface name has been changed. */
1502 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1503 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1504 handleTetherIfaceChange(netType);
1505 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001506 } else {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001507 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001508 removeDefaultRoute(mNetTrackers[netType]);
1509 } else {
1510 removePrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001511 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001512 }
1513 }
1514
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001515 private void addPrivateDnsRoutes(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001516 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001517 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001518 if (p == null) return;
1519 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001520
1521 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001522 log("addPrivateDnsRoutes for " + nt +
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001523 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1524 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001525 if (interfaceName != null && !privateDnsRouteSet) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001526 Collection<InetAddress> dnsList = p.getDnses();
1527 for (InetAddress dns : dnsList) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001528 addHostRoute(nt, dns, 0);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001529 }
1530 nt.privateDnsRouteSet(true);
1531 }
1532 }
1533
1534 private void removePrivateDnsRoutes(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001535 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001536 if (p == null) return;
1537 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001538 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1539 if (interfaceName != null && privateDnsRouteSet) {
1540 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001541 log("removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001542 " (" + interfaceName + ")");
1543 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001544
1545 Collection<InetAddress> dnsList = p.getDnses();
1546 for (InetAddress dns : dnsList) {
1547 if (DBG) log(" removing " + dns);
1548 RouteInfo route = RouteInfo.makeHostRoute(dns);
1549 try {
1550 mNetd.removeRoute(interfaceName, route);
1551 } catch (Exception ex) {
1552 loge("error (" + ex + ") removing dns route " + route);
1553 }
1554 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001555 nt.privateDnsRouteSet(false);
1556 }
1557 }
1558
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001559
1560 private void addDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001561 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001562 if (p == null) return;
1563 String interfaceName = p.getInterfaceName();
Robert Greenwalt5c733972011-02-09 13:56:06 -08001564 if (TextUtils.isEmpty(interfaceName)) return;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001565
Robert Greenwalt355205c2011-05-10 15:05:02 -07001566 for (RouteInfo route : p.getRoutes()) {
Robert Greenwalt5a901292011-04-28 14:28:50 -07001567 //TODO - handle non-default routes
1568 if (route.isDefaultRoute()) {
Robert Greenwalt355205c2011-05-10 15:05:02 -07001569 if (DBG) log("adding default route " + route);
Robert Greenwalt5a901292011-04-28 14:28:50 -07001570 InetAddress gateway = route.getGateway();
Robert Greenwalt355205c2011-05-10 15:05:02 -07001571 if (addHostRoute(nt, gateway, 0)) {
1572 try {
1573 mNetd.addRoute(interfaceName, route);
1574 } catch (Exception e) {
1575 loge("error adding default route " + route);
1576 continue;
1577 }
Robert Greenwalt5a901292011-04-28 14:28:50 -07001578 if (DBG) {
1579 NetworkInfo networkInfo = nt.getNetworkInfo();
1580 log("addDefaultRoute for " + networkInfo.getTypeName() +
1581 " (" + interfaceName + "), GatewayAddr=" +
1582 gateway.getHostAddress());
1583 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001584 } else {
1585 loge("error adding host route for default route " + route);
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001586 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001587 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001588 }
1589 }
1590
1591
1592 public void removeDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001593 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001594 if (p == null) return;
1595 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001596
Robert Greenwalt355205c2011-05-10 15:05:02 -07001597 if (interfaceName == null) return;
1598
1599 for (RouteInfo route : p.getRoutes()) {
1600 //TODO - handle non-default routes
1601 if (route.isDefaultRoute()) {
1602 try {
1603 mNetd.removeRoute(interfaceName, route);
1604 } catch (Exception ex) {
1605 loge("error (" + ex + ") removing default route " + route);
1606 continue;
1607 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001608 if (DBG) {
1609 NetworkInfo networkInfo = nt.getNetworkInfo();
1610 log("removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1611 interfaceName + ")");
1612 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001613 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001614 }
1615 }
1616
1617 /**
1618 * Reads the network specific TCP buffer sizes from SystemProperties
1619 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1620 * wide use
1621 */
1622 public void updateNetworkSettings(NetworkStateTracker nt) {
1623 String key = nt.getTcpBufferSizesPropName();
1624 String bufferSizes = SystemProperties.get(key);
1625
1626 if (bufferSizes.length() == 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001627 loge(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001628
1629 // Setting to default values so we won't be stuck to previous values
1630 key = "net.tcp.buffersize.default";
1631 bufferSizes = SystemProperties.get(key);
1632 }
1633
1634 // Set values in kernel
1635 if (bufferSizes.length() != 0) {
1636 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001637 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001638 + "] which comes from [" + key + "]");
1639 }
1640 setBufferSize(bufferSizes);
1641 }
1642 }
1643
1644 /**
1645 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1646 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1647 *
1648 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1649 * writeMin, writeInitial, writeMax"
1650 */
1651 private void setBufferSize(String bufferSizes) {
1652 try {
1653 String[] values = bufferSizes.split(",");
1654
1655 if (values.length == 6) {
1656 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001657 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1658 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1659 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1660 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1661 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1662 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001663 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001664 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001665 }
1666 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001667 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001668 }
1669 }
1670
Robert Greenwalt2034b912009-08-12 16:08:25 -07001671 /**
1672 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1673 * on the highest priority active net which this process requested.
1674 * If there aren't any, clear it out
1675 */
1676 private void reassessPidDns(int myPid, boolean doBump)
1677 {
Wink Savillee70c6f52010-12-03 12:01:38 -08001678 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001679 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001680 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001681 continue;
1682 }
1683 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001684 if (nt.getNetworkInfo().isConnected() &&
1685 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001686 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001687 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001688 List pids = mNetRequestersPids[i];
1689 for (int j=0; j<pids.size(); j++) {
1690 Integer pid = (Integer)pids.get(j);
1691 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001692 Collection<InetAddress> dnses = p.getDnses();
1693 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001694 if (doBump) {
1695 bumpDns();
1696 }
1697 return;
1698 }
1699 }
1700 }
1701 }
1702 // nothing found - delete
1703 for (int i = 1; ; i++) {
1704 String prop = "net.dns" + i + "." + myPid;
1705 if (SystemProperties.get(prop).length() == 0) {
1706 if (doBump) {
1707 bumpDns();
1708 }
1709 return;
1710 }
1711 SystemProperties.set(prop, "");
1712 }
1713 }
1714
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001715 // return true if results in a change
1716 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001717 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001718 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001719 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001720 String dnsString = dns.getHostAddress();
1721 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1722 changed = true;
1723 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1724 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001725 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001726 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001727 }
1728
1729 private void bumpDns() {
1730 /*
1731 * Bump the property that tells the name resolver library to reread
1732 * the DNS server list from the properties.
1733 */
1734 String propVal = SystemProperties.get("net.dnschange");
1735 int n = 0;
1736 if (propVal.length() != 0) {
1737 try {
1738 n = Integer.parseInt(propVal);
1739 } catch (NumberFormatException e) {}
1740 }
1741 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001742 /*
1743 * Tell the VMs to toss their DNS caches
1744 */
1745 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1746 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08001747 /*
1748 * Connectivity events can happen before boot has completed ...
1749 */
1750 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07001751 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001752 }
1753
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001754 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001755 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001756 NetworkStateTracker nt = mNetTrackers[netType];
1757 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001758 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001759 if (p == null) return;
1760 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001761 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001762 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001763 int j = 1;
Robert Greenwalt94daa182010-09-01 11:34:05 -07001764 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001765 String dnsString = mDefaultDns.getHostAddress();
1766 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1767 if (DBG) {
1768 log("no dns provided - using " + dnsString);
1769 }
1770 changed = true;
1771 SystemProperties.set("net.dns1", dnsString);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001772 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001773 j++;
1774 } else {
1775 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001776 String dnsString = dns.getHostAddress();
1777 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1778 j++;
1779 continue;
1780 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001781 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001782 log("adding dns " + dns + " for " +
Robert Greenwalt94daa182010-09-01 11:34:05 -07001783 nt.getNetworkInfo().getTypeName());
1784 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001785 changed = true;
1786 SystemProperties.set("net.dns" + j++, dnsString);
Robert Greenwalt94daa182010-09-01 11:34:05 -07001787 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001788 }
1789 for (int k=j ; k<mNumDnsEntries; k++) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001790 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1791 if (DBG) log("erasing net.dns" + k);
1792 changed = true;
1793 SystemProperties.set("net.dns" + k, "");
1794 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001795 }
1796 mNumDnsEntries = j;
1797 } else {
1798 // set per-pid dns for attached secondary nets
1799 List pids = mNetRequestersPids[netType];
1800 for (int y=0; y< pids.size(); y++) {
1801 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001802 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001803 }
1804 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001805 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001806 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001807 }
1808
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001809 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001810 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1811 NETWORK_RESTORE_DELAY_PROP_NAME);
1812 if(restoreDefaultNetworkDelayStr != null &&
1813 restoreDefaultNetworkDelayStr.length() != 0) {
1814 try {
1815 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1816 } catch (NumberFormatException e) {
1817 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001818 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001819 // if the system property isn't set, use the value for the apn type
1820 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1821
1822 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1823 (mNetConfigs[networkType] != null)) {
1824 ret = mNetConfigs[networkType].restoreTime;
1825 }
1826 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001827 }
1828
1829 @Override
1830 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001831 if (mContext.checkCallingOrSelfPermission(
1832 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001833 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001834 pw.println("Permission Denial: can't dump ConnectivityService " +
1835 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1836 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001837 return;
1838 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001839 pw.println();
1840 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001841 if (nst != null) {
1842 if (nst.getNetworkInfo().isConnected()) {
1843 pw.println("Active network: " + nst.getNetworkInfo().
1844 getTypeName());
1845 }
1846 pw.println(nst.getNetworkInfo());
1847 pw.println(nst);
1848 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001849 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001850 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001851
1852 pw.println("Network Requester Pids:");
1853 for (int net : mPriorityList) {
1854 String pidString = net + ": ";
1855 for (Object pid : mNetRequestersPids[net]) {
1856 pidString = pidString + pid.toString() + ", ";
1857 }
1858 pw.println(pidString);
1859 }
1860 pw.println();
1861
1862 pw.println("FeatureUsers:");
1863 for (Object requester : mFeatureUsers) {
1864 pw.println(requester.toString());
1865 }
1866 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001867
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001868 synchronized (this) {
1869 pw.println("NetworkTranstionWakeLock is currently " +
1870 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1871 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1872 }
1873 pw.println();
1874
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001875 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07001876
1877 if (mInetLog != null) {
1878 pw.println();
1879 pw.println("Inet condition reports:");
1880 for(int i = 0; i < mInetLog.size(); i++) {
1881 pw.println(mInetLog.get(i));
1882 }
1883 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001884 }
1885
Robert Greenwalt2034b912009-08-12 16:08:25 -07001886 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001887 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07001888 public MyHandler(Looper looper) {
1889 super(looper);
1890 }
1891
The Android Open Source Project28527d22009-03-03 19:31:44 -08001892 @Override
1893 public void handleMessage(Message msg) {
1894 NetworkInfo info;
1895 switch (msg.what) {
1896 case NetworkStateTracker.EVENT_STATE_CHANGED:
1897 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08001898 int type = info.getType();
1899 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08001900
Wink Savillee70c6f52010-12-03 12:01:38 -08001901 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07001902 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08001903 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001904
1905 // Connectivity state changed:
1906 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07001907 // [12-9] Network subtype (for mobile network, as defined
1908 // by TelephonyManager)
1909 // [8-3] Detailed state ordinal (as defined by
1910 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001911 // [2-0] Network type (as defined by ConnectivityManager)
1912 int eventLogParam = (info.getType() & 0x7) |
1913 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1914 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08001915 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07001916 eventLogParam);
1917
1918 if (info.getDetailedState() ==
1919 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001920 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001921 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001922 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001923 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001924 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001925 // the logic here is, handle SUSPENDED the same as
1926 // DISCONNECTED. The only difference being we are
1927 // broadcasting an intent with NetworkInfo that's
1928 // suspended. This allows the applications an
1929 // opportunity to handle DISCONNECTED and SUSPENDED
1930 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001931 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001932 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001933 handleConnect(info);
1934 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001935 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001936 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001937 info = (NetworkInfo) msg.obj;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001938 handleConnectivityChange(info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001939 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001940 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001941 String causedBy = null;
1942 synchronized (ConnectivityService.this) {
1943 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
1944 mNetTransitionWakeLock.isHeld()) {
1945 mNetTransitionWakeLock.release();
1946 causedBy = mNetTransitionWakeLockCausedBy;
1947 }
1948 }
1949 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001950 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001951 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07001952 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001953 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001954 FeatureUser u = (FeatureUser)msg.obj;
1955 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07001956 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001957 case EVENT_INET_CONDITION_CHANGE:
1958 {
1959 int netType = msg.arg1;
1960 int condition = msg.arg2;
1961 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001962 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001963 }
1964 case EVENT_INET_CONDITION_HOLD_END:
1965 {
1966 int netType = msg.arg1;
1967 int sequence = msg.arg2;
1968 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07001969 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001970 }
1971 case EVENT_SET_NETWORK_PREFERENCE:
1972 {
1973 int preference = msg.arg1;
1974 handleSetNetworkPreference(preference);
1975 break;
1976 }
1977 case EVENT_SET_BACKGROUND_DATA:
1978 {
1979 boolean enabled = (msg.arg1 == ENABLED);
1980 handleSetBackgroundData(enabled);
1981 break;
1982 }
1983 case EVENT_SET_MOBILE_DATA:
1984 {
1985 boolean enabled = (msg.arg1 == ENABLED);
1986 handleSetMobileData(enabled);
1987 break;
1988 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001989 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
1990 {
1991 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07001992 break;
1993 }
1994 case EVENT_SET_DEPENDENCY_MET:
1995 {
1996 boolean met = (msg.arg1 == ENABLED);
1997 handleSetDependencyMet(msg.arg2, met);
1998 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001999 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002000 }
2001 }
2002 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002003
2004 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002005 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002006 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002007
2008 if (isTetheringSupported()) {
2009 return mTethering.tether(iface);
2010 } else {
2011 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2012 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002013 }
2014
2015 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002016 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002017 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002018
2019 if (isTetheringSupported()) {
2020 return mTethering.untether(iface);
2021 } else {
2022 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2023 }
2024 }
2025
2026 // javadoc from interface
2027 public int getLastTetherError(String iface) {
2028 enforceTetherAccessPermission();
2029
2030 if (isTetheringSupported()) {
2031 return mTethering.getLastTetherError(iface);
2032 } else {
2033 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2034 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002035 }
2036
2037 // TODO - proper iface API for selection by property, inspection, etc
2038 public String[] getTetherableUsbRegexs() {
2039 enforceTetherAccessPermission();
2040 if (isTetheringSupported()) {
2041 return mTethering.getTetherableUsbRegexs();
2042 } else {
2043 return new String[0];
2044 }
2045 }
2046
2047 public String[] getTetherableWifiRegexs() {
2048 enforceTetherAccessPermission();
2049 if (isTetheringSupported()) {
2050 return mTethering.getTetherableWifiRegexs();
2051 } else {
2052 return new String[0];
2053 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002054 }
2055
Danica Chang96567052010-08-11 14:54:43 -07002056 public String[] getTetherableBluetoothRegexs() {
2057 enforceTetherAccessPermission();
2058 if (isTetheringSupported()) {
2059 return mTethering.getTetherableBluetoothRegexs();
2060 } else {
2061 return new String[0];
2062 }
2063 }
2064
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002065 // TODO - move iface listing, queries, etc to new module
2066 // javadoc from interface
2067 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002068 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002069 return mTethering.getTetherableIfaces();
2070 }
2071
2072 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002073 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002074 return mTethering.getTetheredIfaces();
2075 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002076
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002077 public String[] getTetheringErroredIfaces() {
2078 enforceTetherAccessPermission();
2079 return mTethering.getErroredIfaces();
2080 }
2081
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002082 // if ro.tether.denied = true we default to no tethering
2083 // gservices could set the secure setting to 1 though to enable it on a build where it
2084 // had previously been turned off.
2085 public boolean isTetheringSupported() {
2086 enforceTetherAccessPermission();
2087 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002088 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2089 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2090 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002091 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002092
2093 // An API NetworkStateTrackers can call when they lose their network.
2094 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2095 // whichever happens first. The timer is started by the first caller and not
2096 // restarted by subsequent callers.
2097 public void requestNetworkTransitionWakelock(String forWhom) {
2098 enforceConnectivityInternalPermission();
2099 synchronized (this) {
2100 if (mNetTransitionWakeLock.isHeld()) return;
2101 mNetTransitionWakeLockSerialNumber++;
2102 mNetTransitionWakeLock.acquire();
2103 mNetTransitionWakeLockCausedBy = forWhom;
2104 }
2105 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002106 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002107 mNetTransitionWakeLockSerialNumber, 0),
2108 mNetTransitionWakeLockTimeout);
2109 return;
2110 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002111
Robert Greenwalt986c7412010-09-08 15:24:47 -07002112 // 100 percent is full good, 0 is full bad.
2113 public void reportInetCondition(int networkType, int percentage) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002114 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002115 mContext.enforceCallingOrSelfPermission(
2116 android.Manifest.permission.STATUS_BAR,
2117 "ConnectivityService");
2118
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002119 if (DBG) {
2120 int pid = getCallingPid();
2121 int uid = getCallingUid();
2122 String s = pid + "(" + uid + ") reports inet is " +
2123 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2124 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2125 mInetLog.add(s);
2126 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2127 mInetLog.remove(0);
2128 }
2129 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002130 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002131 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2132 }
2133
2134 private void handleInetConditionChange(int netType, int condition) {
2135 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002136 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002137 netType + ", condition=" + condition +
2138 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2139 }
2140 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002141 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002142 return;
2143 }
2144 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002145 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002146 return;
2147 }
2148 mDefaultInetCondition = condition;
2149 int delay;
2150 if (mInetConditionChangeInFlight == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002151 if (DBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002152 // setup a new hold to debounce this
2153 if (mDefaultInetCondition > 50) {
2154 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2155 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2156 } else {
2157 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2158 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2159 }
2160 mInetConditionChangeInFlight = true;
2161 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2162 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2163 } else {
2164 // we've set the new condition, when this hold ends that will get
2165 // picked up
Wink Savillee70c6f52010-12-03 12:01:38 -08002166 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002167 }
2168 }
2169
2170 private void handleInetConditionHoldEnd(int netType, int sequence) {
2171 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002172 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002173 ", condition =" + mDefaultInetCondition +
2174 ", published condition =" + mDefaultInetConditionPublished);
2175 }
2176 mInetConditionChangeInFlight = false;
2177
2178 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002179 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002180 return;
2181 }
2182 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002183 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002184 return;
2185 }
2186 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002187 if (DBG) log("no change in condition - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002188 return;
2189 }
2190 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2191 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002192 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002193 return;
2194 }
2195 mDefaultInetConditionPublished = mDefaultInetCondition;
2196 sendInetConditionBroadcast(networkInfo);
2197 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002198 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002199
2200 public synchronized ProxyProperties getProxy() {
2201 if (mGlobalProxy != null) return mGlobalProxy;
2202 if (mDefaultProxy != null) return mDefaultProxy;
2203 return null;
2204 }
2205
2206 public void setGlobalProxy(ProxyProperties proxyProperties) {
2207 enforceChangePermission();
2208 synchronized (mGlobalProxyLock) {
2209 if (proxyProperties == mGlobalProxy) return;
2210 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2211 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2212
2213 String host = "";
2214 int port = 0;
2215 String exclList = "";
2216 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2217 mGlobalProxy = new ProxyProperties(proxyProperties);
2218 host = mGlobalProxy.getHost();
2219 port = mGlobalProxy.getPort();
2220 exclList = mGlobalProxy.getExclusionList();
2221 } else {
2222 mGlobalProxy = null;
2223 }
2224 ContentResolver res = mContext.getContentResolver();
2225 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2226 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002227 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002228 exclList);
2229 }
2230
2231 if (mGlobalProxy == null) {
2232 proxyProperties = mDefaultProxy;
2233 }
2234 sendProxyBroadcast(proxyProperties);
2235 }
2236
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002237 private void loadGlobalProxy() {
2238 ContentResolver res = mContext.getContentResolver();
2239 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2240 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2241 String exclList = Settings.Secure.getString(res,
2242 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2243 if (!TextUtils.isEmpty(host)) {
2244 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2245 synchronized (mGlobalProxyLock) {
2246 mGlobalProxy = proxyProperties;
2247 }
2248 }
2249 }
2250
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002251 public ProxyProperties getGlobalProxy() {
2252 synchronized (mGlobalProxyLock) {
2253 return mGlobalProxy;
2254 }
2255 }
2256
2257 private void handleApplyDefaultProxy(int type) {
2258 // check if new default - push it out to all VM if so
2259 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2260 synchronized (this) {
2261 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2262 if (mDefaultProxy == proxy) return;
2263 if (!TextUtils.isEmpty(proxy.getHost())) {
2264 mDefaultProxy = proxy;
2265 } else {
2266 mDefaultProxy = null;
2267 }
2268 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002269 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002270 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2271 if (mGlobalProxy != null) return;
2272 sendProxyBroadcast(proxy);
2273 }
2274
2275 private void handleDeprecatedGlobalHttpProxy() {
2276 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2277 Settings.Secure.HTTP_PROXY);
2278 if (!TextUtils.isEmpty(proxy)) {
2279 String data[] = proxy.split(":");
2280 String proxyHost = data[0];
2281 int proxyPort = 8080;
2282 if (data.length > 1) {
2283 try {
2284 proxyPort = Integer.parseInt(data[1]);
2285 } catch (NumberFormatException e) {
2286 return;
2287 }
2288 }
2289 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2290 setGlobalProxy(p);
2291 }
2292 }
2293
2294 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002295 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savillee70c6f52010-12-03 12:01:38 -08002296 log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002297 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002298 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2299 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002300 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002301 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002302 }
2303
2304 private static class SettingsObserver extends ContentObserver {
2305 private int mWhat;
2306 private Handler mHandler;
2307 SettingsObserver(Handler handler, int what) {
2308 super(handler);
2309 mHandler = handler;
2310 mWhat = what;
2311 }
2312
2313 void observe(Context context) {
2314 ContentResolver resolver = context.getContentResolver();
2315 resolver.registerContentObserver(Settings.Secure.getUriFor(
2316 Settings.Secure.HTTP_PROXY), false, this);
2317 }
2318
2319 @Override
2320 public void onChange(boolean selfChange) {
2321 mHandler.obtainMessage(mWhat).sendToTarget();
2322 }
2323 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002324
Kazuhiro Ondo3a340412011-04-30 20:10:57 -05002325 private void handleTetherIfaceChange(int type) {
2326 String iface = mNetTrackers[type].getLinkProperties().getInterfaceName();
2327
2328 if (isTetheringSupported()) {
2329 mTethering.handleTetherIfaceChange(iface);
2330 }
2331 }
2332
Wink Savillee70c6f52010-12-03 12:01:38 -08002333 private void log(String s) {
2334 Slog.d(TAG, s);
2335 }
2336
2337 private void loge(String s) {
2338 Slog.e(TAG, s);
2339 }
Wink Savillef6b76692011-02-24 17:58:51 -08002340 int convertFeatureToNetworkType(String feature){
2341 int networkType = -1;
2342 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2343 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2344 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2345 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2346 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2347 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2348 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2349 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2350 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2351 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2352 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2353 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2354 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2355 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2356 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2357 }
2358 return networkType;
2359 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002360
2361 private static <T> T checkNotNull(T value, String message) {
2362 if (value == null) {
2363 throw new NullPointerException(message);
2364 }
2365 return value;
2366 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002367}