blob: 9ba90027d708fdacac8b7a796ffe2a29bee1af9f [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 Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070020import static android.net.ConnectivityManager.isNetworkTypeValid;
21import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070022import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070023
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;
Jeff Sharkey21062e72011-05-28 20:56:34 -070041import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080042import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070043import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070044import android.net.Proxy;
45import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070046import android.net.RouteInfo;
Hung-ying Tyan4e723422011-01-19 16:48:38 +080047import android.net.vpn.VpnManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -080048import android.net.wifi.WifiStateTracker;
49import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040050import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080051import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070052import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070053import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070054import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080055import android.os.Looper;
56import android.os.Message;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070057import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070058import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070059import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080060import android.os.ServiceManager;
61import android.os.SystemProperties;
62import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070063import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080064import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080065import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070066import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080067
Chia-chi Yeh75cacd52011-06-15 17:07:27 -070068import com.android.internal.net.VpnConfig;
Robert Greenwalt2034b912009-08-12 16:08:25 -070069import com.android.internal.telephony.Phone;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080070import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070071import com.android.server.connectivity.Vpn;
72
Jeff Sharkey21062e72011-05-28 20:56:34 -070073import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070074import com.google.android.collect.Sets;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080075
The Android Open Source Project28527d22009-03-03 19:31:44 -080076import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070077import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080078import java.io.PrintWriter;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070079import java.net.InetAddress;
80import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -070081import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070082import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070083import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -070084import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070085import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -070086import java.util.List;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070087import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project28527d22009-03-03 19:31:44 -080088
89/**
90 * @hide
91 */
92public class ConnectivityService extends IConnectivityManager.Stub {
93
Robert Greenwalt063dc7d2010-10-05 19:12:26 -070094 private static final boolean DBG = true;
The Android Open Source Project28527d22009-03-03 19:31:44 -080095 private static final String TAG = "ConnectivityService";
96
Jeff Sharkey921ebf22011-05-19 17:12:49 -070097 private static final boolean LOGD_RULES = false;
98
Robert Greenwalt2034b912009-08-12 16:08:25 -070099 // how long to wait before switching back to a radio's default network
100 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
101 // system property that can override the above value
102 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
103 "android.telephony.apn-restore";
104
Robert Greenwaltbd492212011-05-06 17:10:53 -0700105 // used in recursive route setting to add gateways for the host for which
106 // a host route was requested.
107 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
108
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800109 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800110 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800111
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700112 private Vpn mVpn;
113
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700114 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
115 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700116 /** Currently active network rules by UID. */
117 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700118 /** Set of ifaces that are costly. */
119 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700120
The Android Open Source Project28527d22009-03-03 19:31:44 -0800121 /**
122 * Sometimes we want to refer to the individual network state
123 * trackers separately, and sometimes we just want to treat them
124 * abstractly.
125 */
126 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700127
128 /**
129 * A per Net list of the PID's that requested access to the net
130 * used both as a refcount and for per-PID DNS selection
131 */
132 private List mNetRequestersPids[];
133
Irfan Sheriff653e2a22010-06-07 09:03:04 -0700134 private WifiWatchdogService mWifiWatchdogService;
135
Robert Greenwalt2034b912009-08-12 16:08:25 -0700136 // priority order of the nettrackers
137 // (excluding dynamically set mNetworkPreference)
138 // TODO - move mNetworkTypePreference into this
139 private int[] mPriorityList;
140
The Android Open Source Project28527d22009-03-03 19:31:44 -0800141 private Context mContext;
142 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700143 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700144 // 0 is full bad, 100 is full good
145 private int mDefaultInetCondition = 0;
146 private int mDefaultInetConditionPublished = 0;
147 private boolean mInetConditionChangeInFlight = false;
148 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800149
150 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800151
152 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700153 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800154
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800155 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
156
Robert Greenwalt355205c2011-05-10 15:05:02 -0700157 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700158 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700159
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700160 private static final int ENABLED = 1;
161 private static final int DISABLED = 0;
162
163 // Share the event space with NetworkStateTracker (which can't see this
164 // internal class but sends us events). If you change these, change
165 // NetworkStateTracker.java too.
166 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
167 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
168
169 /**
170 * used internally as a delayed event to make us switch back to the
171 * default network
172 */
173 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
174 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
175
176 /**
177 * used internally to change our mobile data enabled flag
178 */
179 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
180 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
181
182 /**
183 * used internally to change our network preference setting
184 * arg1 = networkType to prefer
185 */
186 private static final int EVENT_SET_NETWORK_PREFERENCE =
187 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
188
189 /**
190 * used internally to synchronize inet condition reports
191 * arg1 = networkType
192 * arg2 = condition (0 bad, 100 good)
193 */
194 private static final int EVENT_INET_CONDITION_CHANGE =
195 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
196
197 /**
198 * used internally to mark the end of inet condition hold periods
199 * arg1 = networkType
200 */
201 private static final int EVENT_INET_CONDITION_HOLD_END =
202 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
203
204 /**
205 * used internally to set the background data preference
206 * arg1 = TRUE for enabled, FALSE for disabled
207 */
208 private static final int EVENT_SET_BACKGROUND_DATA =
209 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
210
211 /**
212 * used internally to set enable/disable cellular data
213 * arg1 = ENBALED or DISABLED
214 */
215 private static final int EVENT_SET_MOBILE_DATA =
216 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
217
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700218 /**
219 * used internally to clear a wakelock when transitioning
220 * from one net to another
221 */
222 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
223 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
224
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700225 /**
226 * used internally to reload global proxy settings
227 */
228 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
229 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
230
Robert Greenwalt34848c02011-03-25 13:09:25 -0700231 /**
232 * used internally to set external dependency met/unmet
233 * arg1 = ENABLED (met) or DISABLED (unmet)
234 * arg2 = NetworkType
235 */
236 private static final int EVENT_SET_DEPENDENCY_MET =
237 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
238
Robert Greenwalt2034b912009-08-12 16:08:25 -0700239 private Handler mHandler;
240
241 // list of DeathRecipients used to make sure features are turned off when
242 // a process dies
243 private List mFeatureUsers;
244
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400245 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800246 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400247
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700248 private PowerManager.WakeLock mNetTransitionWakeLock;
249 private String mNetTransitionWakeLockCausedBy = "";
250 private int mNetTransitionWakeLockSerialNumber;
251 private int mNetTransitionWakeLockTimeout;
252
Robert Greenwalt94daa182010-09-01 11:34:05 -0700253 private InetAddress mDefaultDns;
254
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700255 // used in DBG mode to track inet condition reports
256 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
257 private ArrayList mInetLog;
258
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700259 // track the current default http proxy - tell the world if we get a new one (real change)
260 private ProxyProperties mDefaultProxy = null;
261 // track the global proxy.
262 private ProxyProperties mGlobalProxy = null;
263 private final Object mGlobalProxyLock = new Object();
264
265 private SettingsObserver mSettingsObserver;
266
Robert Greenwalt34848c02011-03-25 13:09:25 -0700267 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700268 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700269
Robert Greenwalt12c44552009-12-07 11:33:18 -0800270 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700271 public int mSimultaneity;
272 public int mType;
273 public RadioAttributes(String init) {
274 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700275 mType = Integer.parseInt(fragments[0]);
276 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700277 }
278 }
279 RadioAttributes[] mRadioAttributes;
280
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700281 // the set of network types that can only be enabled by system/sig apps
282 List mProtectedNetworks;
283
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700284 public ConnectivityService(
285 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800286 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800287
Wink Saville775aad62010-09-02 19:23:52 -0700288 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
289 handlerThread.start();
290 mHandler = new MyHandler(handlerThread.getLooper());
291
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800292 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
293 Settings.Secure.BACKGROUND_DATA, 1) == 1);
294
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800295 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800296 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
297 String id = Settings.Secure.getString(context.getContentResolver(),
298 Settings.Secure.ANDROID_ID);
299 if (id != null && id.length() > 0) {
300 String name = new String("android_").concat(id);
301 SystemProperties.set("net.hostname", name);
302 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800303 }
304
Robert Greenwalt94daa182010-09-01 11:34:05 -0700305 // read our default dns server ip
306 String dns = Settings.Secure.getString(context.getContentResolver(),
307 Settings.Secure.DEFAULT_DNS_SERVER);
308 if (dns == null || dns.length() == 0) {
309 dns = context.getResources().getString(
310 com.android.internal.R.string.config_default_dns_server);
311 }
312 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800313 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
314 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800315 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700316 }
317
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700318 mContext = checkNotNull(context, "missing Context");
319 mNetd = checkNotNull(netd, "missing INetworkManagementService");
320 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700321
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700322 try {
323 mPolicyManager.registerListener(mPolicyListener);
324 } catch (RemoteException e) {
325 // ouch, no rules updates means some processes may never get network
326 Slog.e(TAG, "unable to register INetworkPolicyListener", e);
327 }
328
329 final PowerManager powerManager = (PowerManager) context.getSystemService(
330 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700331 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
332 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
333 com.android.internal.R.integer.config_networkTransitionTimeout);
334
Robert Greenwalt2034b912009-08-12 16:08:25 -0700335 mNetTrackers = new NetworkStateTracker[
336 ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700337
The Android Open Source Project28527d22009-03-03 19:31:44 -0800338 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700339
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700340 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700341 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700342
Robert Greenwalt2034b912009-08-12 16:08:25 -0700343 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700344 String[] raStrings = context.getResources().getStringArray(
345 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700346 for (String raString : raStrings) {
347 RadioAttributes r = new RadioAttributes(raString);
348 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800349 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700350 continue;
351 }
352 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800353 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700354 r.mType);
355 continue;
356 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700357 mRadioAttributes[r.mType] = r;
358 }
359
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700360 String[] naStrings = context.getResources().getStringArray(
361 com.android.internal.R.array.networkAttributes);
362 for (String naString : naStrings) {
363 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700364 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700365 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800366 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700367 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700368 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700369 }
Wink Savillef2a62832011-04-07 14:23:45 -0700370 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800371 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700372 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700373 continue;
374 }
Wink Savillef2a62832011-04-07 14:23:45 -0700375 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800376 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700377 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700378 continue;
379 }
Wink Savillef2a62832011-04-07 14:23:45 -0700380 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700381 mNetworksDefined++;
382 } catch(Exception e) {
383 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700384 }
385 }
386
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700387 mProtectedNetworks = new ArrayList<Integer>();
388 int[] protectedNetworks = context.getResources().getIntArray(
389 com.android.internal.R.array.config_protectedNetworks);
390 for (int p : protectedNetworks) {
391 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
392 mProtectedNetworks.add(p);
393 } else {
394 if (DBG) loge("Ignoring protectedNetwork " + p);
395 }
396 }
397
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700398 // high priority first
399 mPriorityList = new int[mNetworksDefined];
400 {
401 int insertionPoint = mNetworksDefined-1;
402 int currentLowest = 0;
403 int nextLowest = 0;
404 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700405 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700406 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700407 if (na.priority < currentLowest) continue;
408 if (na.priority > currentLowest) {
409 if (na.priority < nextLowest || nextLowest == 0) {
410 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700411 }
412 continue;
413 }
Wink Savillef2a62832011-04-07 14:23:45 -0700414 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700415 }
416 currentLowest = nextLowest;
417 nextLowest = 0;
418 }
419 }
420
421 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
422 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700423 mNetRequestersPids[i] = new ArrayList();
424 }
425
426 mFeatureUsers = new ArrayList();
427
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700428 mNumDnsEntries = 0;
429
430 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
431 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800432 /*
433 * Create the network state trackers for Wi-Fi and mobile
434 * data. Maybe this could be done with a factory class,
435 * but it's not clear that it's worth it, given that
436 * the number of different network types is not going
437 * to change very often.
438 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700439 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700440 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700441 case ConnectivityManager.TYPE_WIFI:
Wink Savillee70c6f52010-12-03 12:01:38 -0800442 if (DBG) log("Starting Wifi Service.");
Wink Saville7fabfa22010-08-13 16:11:42 -0700443 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff25be0762010-07-28 09:35:20 -0700444 WifiService wifiService = new WifiService(context);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700445 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff25be0762010-07-28 09:35:20 -0700446 wifiService.checkAndStartWifi();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700447 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Saville7fabfa22010-08-13 16:11:42 -0700448 wst.startMonitoring(context, mHandler);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800449
Irfan Sheriff653e2a22010-06-07 09:03:04 -0700450 //TODO: as part of WWS refactor, create only when needed
Irfan Sheriff25be0762010-07-28 09:35:20 -0700451 mWifiWatchdogService = new WifiWatchdogService(context);
Irfan Sheriff653e2a22010-06-07 09:03:04 -0700452
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700453 break;
454 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700455 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700456 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700457 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700458 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800459 case ConnectivityManager.TYPE_DUMMY:
460 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700461 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800462 mNetTrackers[netType].startMonitoring(context, mHandler);
463 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800464 case ConnectivityManager.TYPE_BLUETOOTH:
465 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
466 mNetTrackers[netType].startMonitoring(context, mHandler);
467 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800468 case ConnectivityManager.TYPE_ETHERNET:
469 mNetTrackers[netType] = EthernetDataTracker.getInstance();
470 mNetTrackers[netType].startMonitoring(context, mHandler);
471 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700472 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800473 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700474 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700475 continue;
476 }
477 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800478
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700479 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
480 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
481
482 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700483 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700484 mTethering.getTetherableWifiRegexs().length != 0 ||
485 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700486 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800487
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700488 mVpn = new Vpn(mContext, new VpnCallback());
489
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700490 try {
491 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700492 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700493 } catch (RemoteException e) {
494 loge("Error registering observer :" + e);
495 }
496
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700497 if (DBG) {
498 mInetLog = new ArrayList();
499 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700500
501 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
502 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800503
504 loadGlobalProxy();
Hung-ying Tyan4e723422011-01-19 16:48:38 +0800505
506 VpnManager.startVpnService(context);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800507 }
508
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700509
The Android Open Source Project28527d22009-03-03 19:31:44 -0800510 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700511 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800512 * @param preference the new preference
513 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700514 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800515 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700516
517 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800518 }
519
520 public int getNetworkPreference() {
521 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700522 int preference;
523 synchronized(this) {
524 preference = mNetworkPreference;
525 }
526 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800527 }
528
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700529 private void handleSetNetworkPreference(int preference) {
530 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700531 mNetConfigs[preference] != null &&
532 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700533 if (mNetworkPreference != preference) {
534 final ContentResolver cr = mContext.getContentResolver();
535 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
536 synchronized(this) {
537 mNetworkPreference = preference;
538 }
539 enforcePreference();
540 }
541 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800542 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700543
The Android Open Source Project28527d22009-03-03 19:31:44 -0800544 private int getPersistedNetworkPreference() {
545 final ContentResolver cr = mContext.getContentResolver();
546
547 final int networkPrefSetting = Settings.Secure
548 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
549 if (networkPrefSetting != -1) {
550 return networkPrefSetting;
551 }
552
553 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
554 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700555
The Android Open Source Project28527d22009-03-03 19:31:44 -0800556 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700557 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800558 * In this method, we only tear down a non-preferred network. Establishing
559 * a connection to the preferred network is taken care of when we handle
560 * the disconnect event from the non-preferred network
561 * (see {@link #handleDisconnect(NetworkInfo)}).
562 */
563 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700564 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800565 return;
566
Robert Greenwalt2034b912009-08-12 16:08:25 -0700567 if (!mNetTrackers[mNetworkPreference].isAvailable())
568 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800569
Robert Greenwalt2034b912009-08-12 16:08:25 -0700570 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700571 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700572 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700573 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800574 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700575 " in enforcePreference");
576 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700577 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800578 }
579 }
580 }
581
582 private boolean teardown(NetworkStateTracker netTracker) {
583 if (netTracker.teardown()) {
584 netTracker.setTeardownRequested(true);
585 return true;
586 } else {
587 return false;
588 }
589 }
590
591 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700592 * Check if UID should be blocked from using the network represented by the
593 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700594 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700595 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
596 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700597
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700598 final boolean networkCostly;
599 final int uidRules;
600 synchronized (mRulesLock) {
601 networkCostly = mMeteredIfaces.contains(iface);
602 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700603 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700604
605 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
606 return true;
607 }
608
609 // no restrictive rules; network is visible
610 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700611 }
612
613 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700614 * Return a filtered {@link NetworkInfo}, potentially marked
615 * {@link DetailedState#BLOCKED} based on
616 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700617 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700618 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
619 NetworkInfo info = tracker.getNetworkInfo();
620 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700621 // network is blocked; clone and override state
622 info = new NetworkInfo(info);
623 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700624 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700625 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700626 }
627
628 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800629 * Return NetworkInfo for the active (i.e., connected) network interface.
630 * It is assumed that at most one network is active at a time. If more
631 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700632 * @return the info for the active network, or {@code null} if none is
633 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800634 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700635 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800636 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700637 enforceAccessPermission();
638 final int uid = Binder.getCallingUid();
639 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800640 }
641
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700642 @Override
643 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
644 enforceConnectivityInternalPermission();
645 return getNetworkInfo(mActiveDefaultNetwork, uid);
646 }
647
648 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800649 public NetworkInfo getNetworkInfo(int networkType) {
650 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700651 final int uid = Binder.getCallingUid();
652 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800653 }
654
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700655 private NetworkInfo getNetworkInfo(int networkType, int uid) {
656 NetworkInfo info = null;
657 if (isNetworkTypeValid(networkType)) {
658 final NetworkStateTracker tracker = mNetTrackers[networkType];
659 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700660 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700661 }
662 }
663 return info;
664 }
665
666 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800667 public NetworkInfo[] getAllNetworkInfo() {
668 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700669 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700670 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700671 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700672 for (NetworkStateTracker tracker : mNetTrackers) {
673 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700674 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700675 }
676 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800677 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700678 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800679 }
680
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700681 /**
682 * Return LinkProperties for the active (i.e., connected) default
683 * network interface. It is assumed that at most one default network
684 * is active at a time. If more than one is active, it is indeterminate
685 * which will be returned.
686 * @return the ip properties for the active network, or {@code null} if
687 * none is active
688 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700689 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700690 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700691 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700692 }
693
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700694 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700695 public LinkProperties getLinkProperties(int networkType) {
696 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700697 if (isNetworkTypeValid(networkType)) {
698 final NetworkStateTracker tracker = mNetTrackers[networkType];
699 if (tracker != null) {
700 return tracker.getLinkProperties();
701 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700702 }
703 return null;
704 }
705
Jeff Sharkey21062e72011-05-28 20:56:34 -0700706 @Override
707 public NetworkState[] getAllNetworkState() {
708 enforceAccessPermission();
709 final int uid = Binder.getCallingUid();
710 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700711 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700712 for (NetworkStateTracker tracker : mNetTrackers) {
713 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700714 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700715 result.add(new NetworkState(
716 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
717 }
718 }
719 }
720 return result.toArray(new NetworkState[result.size()]);
721 }
722
The Android Open Source Project28527d22009-03-03 19:31:44 -0800723 public boolean setRadios(boolean turnOn) {
724 boolean result = true;
725 enforceChangePermission();
726 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700727 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800728 }
729 return result;
730 }
731
732 public boolean setRadio(int netType, boolean turnOn) {
733 enforceChangePermission();
734 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
735 return false;
736 }
737 NetworkStateTracker tracker = mNetTrackers[netType];
738 return tracker != null && tracker.setRadio(turnOn);
739 }
740
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700741 /**
742 * Used to notice when the calling process dies so we can self-expire
743 *
744 * Also used to know if the process has cleaned up after itself when
745 * our auto-expire timer goes off. The timer has a link to an object.
746 *
747 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700748 private class FeatureUser implements IBinder.DeathRecipient {
749 int mNetworkType;
750 String mFeature;
751 IBinder mBinder;
752 int mPid;
753 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800754 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700755
756 FeatureUser(int type, String feature, IBinder binder) {
757 super();
758 mNetworkType = type;
759 mFeature = feature;
760 mBinder = binder;
761 mPid = getCallingPid();
762 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800763 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700764
Robert Greenwalt2034b912009-08-12 16:08:25 -0700765 try {
766 mBinder.linkToDeath(this, 0);
767 } catch (RemoteException e) {
768 binderDied();
769 }
770 }
771
772 void unlinkDeathRecipient() {
773 mBinder.unlinkToDeath(this, 0);
774 }
775
776 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800777 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800778 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
779 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700780 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700781 }
782
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700783 public void expire() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800784 log("ConnectivityService FeatureUser expire(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800785 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
786 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700787 stopUsingNetworkFeature(this, false);
788 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800789
790 public String toString() {
791 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
792 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
793 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700794 }
795
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700796 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700797 public int startUsingNetworkFeature(int networkType, String feature,
798 IBinder binder) {
799 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800800 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700801 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800802 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700803 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700804 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700805 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800806 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700807
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700808 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700809
810 // TODO - move this into the MobileDataStateTracker
811 int usedNetworkType = networkType;
812 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800813 usedNetworkType = convertFeatureToNetworkType(feature);
814 if (usedNetworkType < 0) {
815 Slog.e(TAG, "Can't match any netTracker!");
816 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700817 }
818 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700819
820 if (mProtectedNetworks.contains(usedNetworkType)) {
821 enforceConnectivityInternalPermission();
822 }
823
Robert Greenwalt2034b912009-08-12 16:08:25 -0700824 NetworkStateTracker network = mNetTrackers[usedNetworkType];
825 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800826 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700827 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700828 NetworkStateTracker radio = mNetTrackers[networkType];
829 NetworkInfo ni = network.getNetworkInfo();
830
831 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800832 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800833 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
834 return Phone.APN_TYPE_NOT_AVAILABLE;
835 } else {
836 // else make the attempt anyway - probably giving REQUEST_STARTED below
837 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700838 }
839
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700840 synchronized(this) {
841 mFeatureUsers.add(f);
842 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
843 // this gets used for per-pid dns when connected
844 mNetRequestersPids[usedNetworkType].add(currentPid);
845 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700846 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700847
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700848 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
849
850 if (restoreTimer >= 0) {
851 mHandler.sendMessageDelayed(
852 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
853 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700854
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700855 if ((ni.isConnectedOrConnecting() == true) &&
856 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700857 if (ni.isConnected() == true) {
858 // add the pid-specific dns
Robert Greenwalt3afbead2010-07-23 15:46:26 -0700859 handleDnsConfigurationChange(networkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800860 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700861 return Phone.APN_ALREADY_ACTIVE;
862 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800863 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700864 return Phone.APN_REQUEST_STARTED;
865 }
866
867 // check if the radio in play can make another contact
868 // assume if cannot for now
869
Wink Savillee70c6f52010-12-03 12:01:38 -0800870 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700871 network.reconnect();
872 return Phone.APN_REQUEST_STARTED;
873 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800874 // need to remember this unsupported request so we respond appropriately on stop
875 synchronized(this) {
876 mFeatureUsers.add(f);
877 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
878 // this gets used for per-pid dns when connected
879 mNetRequestersPids[usedNetworkType].add(currentPid);
880 }
881 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700882 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700883 }
884 }
885 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800886 }
887
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700888 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800889 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700890 enforceChangePermission();
891
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700892 int pid = getCallingPid();
893 int uid = getCallingUid();
894
895 FeatureUser u = null;
896 boolean found = false;
897
898 synchronized(this) {
899 for (int i = 0; i < mFeatureUsers.size() ; i++) {
900 u = (FeatureUser)mFeatureUsers.get(i);
901 if (uid == u.mUid && pid == u.mPid &&
902 networkType == u.mNetworkType &&
903 TextUtils.equals(feature, u.mFeature)) {
904 found = true;
905 break;
906 }
907 }
908 }
909 if (found && u != null) {
910 // stop regardless of how many other time this proc had called start
911 return stopUsingNetworkFeature(u, true);
912 } else {
913 // none found!
Wink Savillee70c6f52010-12-03 12:01:38 -0800914 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700915 return 1;
916 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700917 }
918
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700919 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
920 int networkType = u.mNetworkType;
921 String feature = u.mFeature;
922 int pid = u.mPid;
923 int uid = u.mUid;
924
925 NetworkStateTracker tracker = null;
926 boolean callTeardown = false; // used to carry our decision outside of sync block
927
Robert Greenwalt2034b912009-08-12 16:08:25 -0700928 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800929 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700930 ": " + feature);
931 }
Robert Greenwalt28f43012009-10-06 17:52:40 -0700932
The Android Open Source Project28527d22009-03-03 19:31:44 -0800933 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
934 return -1;
935 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700936
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700937 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
938 // sync block
939 synchronized(this) {
940 // check if this process still has an outstanding start request
941 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800942 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700943 return 1;
944 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700945 u.unlinkDeathRecipient();
946 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
947 // If we care about duplicate requests, check for that here.
948 //
949 // This is done to support the extension of a request - the app
950 // can request we start the network feature again and renew the
951 // auto-shutoff delay. Normal "stop" calls from the app though
952 // do not pay attention to duplicate requests - in effect the
953 // API does not refcount and a single stop will counter multiple starts.
954 if (ignoreDups == false) {
955 for (int i = 0; i < mFeatureUsers.size() ; i++) {
956 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
957 if (x.mUid == u.mUid && x.mPid == u.mPid &&
958 x.mNetworkType == u.mNetworkType &&
959 TextUtils.equals(x.mFeature, u.mFeature)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800960 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700961 return 1;
962 }
963 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700964 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700965
966 // TODO - move to MobileDataStateTracker
967 int usedNetworkType = networkType;
968 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800969 usedNetworkType = convertFeatureToNetworkType(feature);
970 if (usedNetworkType < 0) {
971 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700972 }
973 }
974 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700975 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800976 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700977 return -1;
978 }
979 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700980 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700981 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -0800982 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700983 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800984 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700985 "others still using it");
986 return 1;
987 }
988 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -0800989 } else {
990 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700991 }
992 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800993 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700994 if (callTeardown) {
995 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700996 return 1;
997 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -0700998 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700999 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001000 }
1001
1002 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001003 * @deprecated use requestRouteToHostAddress instead
1004 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001005 * Ensure that a network route exists to deliver traffic to the specified
1006 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001007 * @param networkType the type of the network over which traffic to the
1008 * specified host is to be routed
1009 * @param hostAddress the IP address of the host to which the route is
1010 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001011 * @return {@code true} on success, {@code false} on failure
1012 */
1013 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001014 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1015
1016 if (inetAddress == null) {
1017 return false;
1018 }
1019
1020 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1021 }
1022
1023 /**
1024 * Ensure that a network route exists to deliver traffic to the specified
1025 * host via the specified network interface.
1026 * @param networkType the type of the network over which traffic to the
1027 * specified host is to be routed
1028 * @param hostAddress the IP address of the host to which the route is
1029 * desired
1030 * @return {@code true} on success, {@code false} on failure
1031 */
1032 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001033 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001034 if (mProtectedNetworks.contains(networkType)) {
1035 enforceConnectivityInternalPermission();
1036 }
1037
The Android Open Source Project28527d22009-03-03 19:31:44 -08001038 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1039 return false;
1040 }
1041 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001042
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001043 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1044 tracker.isTeardownRequested()) {
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001045 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001046 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001047 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001048 }
1049 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001050 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001051 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001052 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001053 return addHostRoute(tracker, addr, 0);
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001054 } catch (UnknownHostException e) {}
1055 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001056 }
1057
1058 /**
1059 * Ensure that a network route exists to deliver traffic to the specified
1060 * host via the mobile data network.
1061 * @param hostAddress the IP address of the host to which the route is desired,
1062 * in network byte order.
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001063 * TODO - deprecate
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001064 * @return {@code true} on success, {@code false} on failure
1065 */
Robert Greenwaltbd492212011-05-06 17:10:53 -07001066 private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress, int cycleCount) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001067 LinkProperties lp = nt.getLinkProperties();
1068 if ((lp == null) || (hostAddress == null)) return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001069
Robert Greenwaltbd492212011-05-06 17:10:53 -07001070 String interfaceName = lp.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001071 if (DBG) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001072 log("Requested host route to " + hostAddress + "(" + interfaceName + "), cycleCount=" +
1073 cycleCount);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001074 }
Robert Greenwaltbd492212011-05-06 17:10:53 -07001075 if (interfaceName == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001076 if (DBG) loge("addHostRoute failed due to null interface name");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001077 return false;
1078 }
Robert Greenwaltbd492212011-05-06 17:10:53 -07001079
1080 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), hostAddress);
Robert Greenwalt355205c2011-05-10 15:05:02 -07001081 InetAddress gatewayAddress = null;
Robert Greenwaltbd492212011-05-06 17:10:53 -07001082 if (bestRoute != null) {
Robert Greenwalt355205c2011-05-10 15:05:02 -07001083 gatewayAddress = bestRoute.getGateway();
Robert Greenwaltbd492212011-05-06 17:10:53 -07001084 // if the best route is ourself, don't relf-reference, just add the host route
Robert Greenwalt355205c2011-05-10 15:05:02 -07001085 if (hostAddress.equals(gatewayAddress)) gatewayAddress = null;
Robert Greenwaltbd492212011-05-06 17:10:53 -07001086 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001087 if (gatewayAddress != null) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001088 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1089 loge("Error adding hostroute - too much recursion");
1090 return false;
1091 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001092 if (!addHostRoute(nt, gatewayAddress, cycleCount+1)) return false;
Robert Greenwaltbd492212011-05-06 17:10:53 -07001093 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001094
1095 RouteInfo route = RouteInfo.makeHostRoute(hostAddress, gatewayAddress);
1096
1097 try {
1098 mNetd.addRoute(interfaceName, route);
1099 return true;
1100 } catch (Exception ex) {
1101 return false;
1102 }
Robert Greenwaltbd492212011-05-06 17:10:53 -07001103 }
1104
1105 // TODO support the removal of single host routes. Keep a ref count of them so we
1106 // aren't over-zealous
1107 private boolean removeHostRoute(NetworkStateTracker nt, InetAddress hostAddress) {
1108 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001109 }
1110
1111 /**
1112 * @see ConnectivityManager#getBackgroundDataSetting()
1113 */
1114 public boolean getBackgroundDataSetting() {
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001115 return mBackgroundDataEnabled.get();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001116 }
Robert Greenwalt0659da32009-07-16 17:21:39 -07001117
The Android Open Source Project28527d22009-03-03 19:31:44 -08001118 /**
1119 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1120 */
1121 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1122 mContext.enforceCallingOrSelfPermission(
1123 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1124 "ConnectivityService");
Robert Greenwalt0659da32009-07-16 17:21:39 -07001125
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001126 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1127
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001128 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1129 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1130 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001131
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001132 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwalt0ffdef12011-02-25 13:44:09 -08001133 Settings.Secure.putInt(mContext.getContentResolver(),
1134 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1135 Intent broadcast = new Intent(
1136 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1137 mContext.sendBroadcast(broadcast);
Robert Greenwalt0659da32009-07-16 17:21:39 -07001138 }
1139
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001140 /**
1141 * @see ConnectivityManager#getMobileDataEnabled()
1142 */
1143 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001144 // TODO: This detail should probably be in DataConnectionTracker's
1145 // which is where we store the value and maybe make this
1146 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001147 enforceAccessPermission();
1148 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1149 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savillee70c6f52010-12-03 12:01:38 -08001150 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001151 return retVal;
1152 }
1153
Robert Greenwalt34848c02011-03-25 13:09:25 -07001154 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001155 enforceConnectivityInternalPermission();
1156
Robert Greenwalt34848c02011-03-25 13:09:25 -07001157 if (DBG) {
1158 log("setDataDependency(" + networkType + ", " + met + ")");
1159 }
1160 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1161 (met ? ENABLED : DISABLED), networkType));
1162 }
1163
1164 private void handleSetDependencyMet(int networkType, boolean met) {
1165 if (mNetTrackers[networkType] != null) {
1166 if (DBG) {
1167 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1168 }
1169 mNetTrackers[networkType].setDependencyMet(met);
1170 }
1171 }
1172
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001173 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1174 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001175 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001176 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001177 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001178
1179 if (LOGD_RULES) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001180 Slog.d(TAG, "onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001181 }
1182
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001183 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001184 // skip update when we've already applied rules
1185 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1186 if (oldRules == uidRules) return;
1187
1188 mUidRules.put(uid, uidRules);
1189 }
1190
1191 // TODO: dispatch into NMS to push rules towards kernel module
1192 // TODO: notify UID when it has requested targeted updates
1193 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001194
1195 @Override
1196 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1197 // only someone like NPMS should only be calling us
1198 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1199
1200 if (LOGD_RULES) {
1201 Slog.d(TAG,
1202 "onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1203 }
1204
1205 synchronized (mRulesLock) {
1206 mMeteredIfaces.clear();
1207 for (String iface : meteredIfaces) {
1208 mMeteredIfaces.add(iface);
1209 }
1210 }
1211 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001212 };
1213
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001214 /**
1215 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1216 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001217 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001218 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001219 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001220
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001221 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001222 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001223 }
1224
1225 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001226 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1227 if (DBG) {
1228 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001229 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001230 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001231 }
1232 }
1233
The Android Open Source Project28527d22009-03-03 19:31:44 -08001234 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001235 mContext.enforceCallingOrSelfPermission(
1236 android.Manifest.permission.ACCESS_NETWORK_STATE,
1237 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001238 }
1239
1240 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001241 mContext.enforceCallingOrSelfPermission(
1242 android.Manifest.permission.CHANGE_NETWORK_STATE,
1243 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001244 }
1245
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001246 // TODO Make this a special check when it goes public
1247 private void enforceTetherChangePermission() {
1248 mContext.enforceCallingOrSelfPermission(
1249 android.Manifest.permission.CHANGE_NETWORK_STATE,
1250 "ConnectivityService");
1251 }
1252
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001253 private void enforceTetherAccessPermission() {
1254 mContext.enforceCallingOrSelfPermission(
1255 android.Manifest.permission.ACCESS_NETWORK_STATE,
1256 "ConnectivityService");
1257 }
1258
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001259 private void enforceConnectivityInternalPermission() {
1260 mContext.enforceCallingOrSelfPermission(
1261 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1262 "ConnectivityService");
1263 }
1264
The Android Open Source Project28527d22009-03-03 19:31:44 -08001265 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001266 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1267 * network, we ignore it. If it is for the active network, we send out a
1268 * broadcast. But first, we check whether it might be possible to connect
1269 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001270 * @param info the {@code NetworkInfo} for the network
1271 */
1272 private void handleDisconnect(NetworkInfo info) {
1273
Robert Greenwalt2034b912009-08-12 16:08:25 -07001274 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001275
Robert Greenwalt2034b912009-08-12 16:08:25 -07001276 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001277 /*
1278 * If the disconnected network is not the active one, then don't report
1279 * this as a loss of connectivity. What probably happened is that we're
1280 * getting the disconnect for a network that we explicitly disabled
1281 * in accordance with network preference policies.
1282 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001283 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001284 List pids = mNetRequestersPids[prevNetType];
1285 for (int i = 0; i<pids.size(); i++) {
1286 Integer pid = (Integer)pids.get(i);
1287 // will remove them because the net's no longer connected
1288 // need to do this now as only now do we know the pids and
1289 // can properly null things that are no longer referenced.
1290 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001291 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001292 }
1293
The Android Open Source Project28527d22009-03-03 19:31:44 -08001294 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1295 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1296 if (info.isFailover()) {
1297 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1298 info.setFailover(false);
1299 }
1300 if (info.getReason() != null) {
1301 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1302 }
1303 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001304 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1305 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001306 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001307
Robert Greenwalt34848c02011-03-25 13:09:25 -07001308 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001309 tryFailover(prevNetType);
1310 if (mActiveDefaultNetwork != -1) {
1311 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001312 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1313 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001314 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001315 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1316 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001317 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001318 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001319
1320 // Reset interface if no other connections are using the same interface
1321 boolean doReset = true;
1322 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1323 if (linkProperties != null) {
1324 String oldIface = linkProperties.getInterfaceName();
1325 if (TextUtils.isEmpty(oldIface) == false) {
1326 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1327 if (networkStateTracker == null) continue;
1328 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1329 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1330 LinkProperties l = networkStateTracker.getLinkProperties();
1331 if (l == null) continue;
1332 if (oldIface.equals(l.getInterfaceName())) {
1333 doReset = false;
1334 break;
1335 }
1336 }
1337 }
1338 }
1339 }
1340
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001341 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001342 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001343
1344 sendStickyBroadcast(intent);
1345 /*
1346 * If the failover network is already connected, then immediately send
1347 * out a followup broadcast indicating successful failover
1348 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001349 if (mActiveDefaultNetwork != -1) {
1350 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001351 }
1352 }
1353
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001354 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001355 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001356 * If this is a default network, check if other defaults are available.
1357 * Try to reconnect on all available and let them hash it out when
1358 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001359 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001360 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001361 if (mActiveDefaultNetwork == prevNetType) {
1362 mActiveDefaultNetwork = -1;
1363 }
1364
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001365 // don't signal a reconnect for anything lower or equal priority than our
1366 // current connected default
1367 // TODO - don't filter by priority now - nice optimization but risky
1368// int currentPriority = -1;
1369// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001370// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001371// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001372 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001373 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001374 if (mNetConfigs[checkType] == null) continue;
1375 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001376
1377// Enabling the isAvailable() optimization caused mobile to not get
1378// selected if it was in the middle of error handling. Specifically
1379// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1380// would not be available and we wouldn't get connected to anything.
1381// So removing the isAvailable() optimization below for now. TODO: This
1382// optimization should work and we need to investigate why it doesn't work.
1383// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1384// complete before it is really complete.
1385// if (!mNetTrackers[checkType].isAvailable()) continue;
1386
Robert Greenwalt34848c02011-03-25 13:09:25 -07001387// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001388
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001389 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1390 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1391 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1392 checkInfo.setFailover(true);
1393 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001394 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001395 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001396 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001397 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001398 }
1399
1400 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001401 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1402 }
1403
1404 private void sendInetConditionBroadcast(NetworkInfo info) {
1405 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1406 }
1407
1408 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1409 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001410 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1411 if (info.isFailover()) {
1412 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1413 info.setFailover(false);
1414 }
1415 if (info.getReason() != null) {
1416 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1417 }
1418 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001419 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1420 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001421 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001422 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001423 sendStickyBroadcast(intent);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001424 }
1425
1426 /**
1427 * Called when an attempt to fail over to another network has failed.
1428 * @param info the {@link NetworkInfo} for the failed network
1429 */
1430 private void handleConnectionFailure(NetworkInfo info) {
1431 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001432
Robert Greenwalt2034b912009-08-12 16:08:25 -07001433 String reason = info.getReason();
1434 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001435
Robert Greenwalte981bc52010-10-08 16:35:52 -07001436 String reasonText;
1437 if (reason == null) {
1438 reasonText = ".";
1439 } else {
1440 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001441 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001442 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001443
1444 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1445 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1446 if (getActiveNetworkInfo() == null) {
1447 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1448 }
1449 if (reason != null) {
1450 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1451 }
1452 if (extraInfo != null) {
1453 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1454 }
1455 if (info.isFailover()) {
1456 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1457 info.setFailover(false);
1458 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001459
Robert Greenwalt34848c02011-03-25 13:09:25 -07001460 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001461 tryFailover(info.getType());
1462 if (mActiveDefaultNetwork != -1) {
1463 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001464 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1465 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001466 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001467 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1468 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001469 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001470
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001471 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001472 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001473 /*
1474 * If the failover network is already connected, then immediately send
1475 * out a followup broadcast indicating successful failover
1476 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001477 if (mActiveDefaultNetwork != -1) {
1478 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001479 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001480 }
1481
1482 private void sendStickyBroadcast(Intent intent) {
1483 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001484 if (!mSystemReady) {
1485 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001486 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001487 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1488 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001489 }
1490 }
1491
1492 void systemReady() {
1493 synchronized(this) {
1494 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001495 if (mInitialBroadcast != null) {
1496 mContext.sendStickyBroadcast(mInitialBroadcast);
1497 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001498 }
1499 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001500 // load the global proxy at startup
1501 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001502 }
1503
1504 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001505 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001506
1507 // snapshot isFailover, because sendConnectedBroadcast() resets it
1508 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001509 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001510
Robert Greenwalt2034b912009-08-12 16:08:25 -07001511 // if this is a default net and other default is running
1512 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001513 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001514 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1515 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001516 mNetConfigs[mActiveDefaultNetwork].priority >
1517 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001518 mNetworkPreference == mActiveDefaultNetwork) {
1519 // don't accept this one
Wink Savillee70c6f52010-12-03 12:01:38 -08001520 if (DBG) {
1521 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001522 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001523 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001524 teardown(thisNet);
1525 return;
1526 } else {
1527 // tear down the other
1528 NetworkStateTracker otherNet =
1529 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001530 if (DBG) {
1531 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001532 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001533 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001534 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001535 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001536 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001537 return;
1538 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001539 }
1540 }
1541 synchronized (ConnectivityService.this) {
1542 // have a new default network, release the transition wakelock in a second
1543 // if it's held. The second pause is to allow apps to reconnect over the
1544 // new network
1545 if (mNetTransitionWakeLock.isHeld()) {
1546 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001547 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001548 mNetTransitionWakeLockSerialNumber, 0),
1549 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001550 }
1551 }
1552 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001553 // this will cause us to come up initially as unconnected and switching
1554 // to connected after our normal pause unless somebody reports us as reall
1555 // disconnected
1556 mDefaultInetConditionPublished = 0;
1557 mDefaultConnectionSequence++;
1558 mInetConditionChangeInFlight = false;
1559 // Don't do this - if we never sign in stay, grey
1560 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001561 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001562 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001563 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001564 handleConnectivityChange(type, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001565 sendConnectedBroadcast(info);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001566 }
1567
The Android Open Source Project28527d22009-03-03 19:31:44 -08001568 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001569 * After a change in the connectivity state of a network. We're mainly
1570 * concerned with making sure that the list of DNS servers is set up
1571 * according to which networks are connected, and ensuring that the
1572 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001573 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001574 private void handleConnectivityChange(int netType, boolean doReset) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001575 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001576 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001577 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001578 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001579 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001580
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001581 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001582 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001583 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001584 addDefaultRoute(mNetTrackers[netType]);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001585 } else {
Robert Greenwalt1e2f2862011-04-01 10:51:22 -07001586 // many radios add a default route even when we don't want one.
1587 // remove the default route unless we need it for our active network
1588 if (mActiveDefaultNetwork != -1) {
1589 LinkProperties defaultLinkProperties =
1590 mNetTrackers[mActiveDefaultNetwork].getLinkProperties();
1591 LinkProperties newLinkProperties =
1592 mNetTrackers[netType].getLinkProperties();
1593 String defaultIface = defaultLinkProperties.getInterfaceName();
1594 if (defaultIface != null &&
1595 !defaultIface.equals(newLinkProperties.getInterfaceName())) {
1596 removeDefaultRoute(mNetTrackers[netType]);
1597 }
1598 }
Michael Jurka837e3642011-03-30 19:54:08 -07001599 addPrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001600 }
1601 } else {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001602 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001603 removeDefaultRoute(mNetTrackers[netType]);
1604 } else {
1605 removePrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001606 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001607 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001608
1609 if (doReset) {
1610 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1611 if (linkProperties != null) {
1612 String iface = linkProperties.getInterfaceName();
1613 if (TextUtils.isEmpty(iface) == false) {
1614 if (DBG) log("resetConnections(" + iface + ")");
1615 NetworkUtils.resetConnections(iface);
1616 }
1617 }
1618 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001619 }
1620
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001621 private void addPrivateDnsRoutes(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001622 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001623 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001624 if (p == null) return;
1625 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001626
1627 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001628 log("addPrivateDnsRoutes for " + nt +
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001629 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1630 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001631 if (interfaceName != null && !privateDnsRouteSet) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001632 Collection<InetAddress> dnsList = p.getDnses();
1633 for (InetAddress dns : dnsList) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001634 addHostRoute(nt, dns, 0);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001635 }
1636 nt.privateDnsRouteSet(true);
1637 }
1638 }
1639
1640 private void removePrivateDnsRoutes(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001641 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001642 if (p == null) return;
1643 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001644 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1645 if (interfaceName != null && privateDnsRouteSet) {
1646 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001647 log("removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001648 " (" + interfaceName + ")");
1649 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001650
1651 Collection<InetAddress> dnsList = p.getDnses();
1652 for (InetAddress dns : dnsList) {
1653 if (DBG) log(" removing " + dns);
1654 RouteInfo route = RouteInfo.makeHostRoute(dns);
1655 try {
1656 mNetd.removeRoute(interfaceName, route);
1657 } catch (Exception ex) {
1658 loge("error (" + ex + ") removing dns route " + route);
1659 }
1660 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001661 nt.privateDnsRouteSet(false);
1662 }
1663 }
1664
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001665
1666 private void addDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001667 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001668 if (p == null) return;
1669 String interfaceName = p.getInterfaceName();
Robert Greenwalt5c733972011-02-09 13:56:06 -08001670 if (TextUtils.isEmpty(interfaceName)) return;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001671
Robert Greenwalt355205c2011-05-10 15:05:02 -07001672 for (RouteInfo route : p.getRoutes()) {
Robert Greenwalt5a901292011-04-28 14:28:50 -07001673 //TODO - handle non-default routes
1674 if (route.isDefaultRoute()) {
Robert Greenwalt355205c2011-05-10 15:05:02 -07001675 if (DBG) log("adding default route " + route);
Robert Greenwalt5a901292011-04-28 14:28:50 -07001676 InetAddress gateway = route.getGateway();
Robert Greenwalt355205c2011-05-10 15:05:02 -07001677 if (addHostRoute(nt, gateway, 0)) {
1678 try {
1679 mNetd.addRoute(interfaceName, route);
1680 } catch (Exception e) {
1681 loge("error adding default route " + route);
1682 continue;
1683 }
Robert Greenwalt5a901292011-04-28 14:28:50 -07001684 if (DBG) {
1685 NetworkInfo networkInfo = nt.getNetworkInfo();
1686 log("addDefaultRoute for " + networkInfo.getTypeName() +
1687 " (" + interfaceName + "), GatewayAddr=" +
1688 gateway.getHostAddress());
1689 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001690 } else {
1691 loge("error adding host route for default route " + route);
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001692 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001693 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001694 }
1695 }
1696
1697
1698 public void removeDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001699 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001700 if (p == null) return;
1701 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001702
Robert Greenwalt355205c2011-05-10 15:05:02 -07001703 if (interfaceName == null) return;
1704
1705 for (RouteInfo route : p.getRoutes()) {
1706 //TODO - handle non-default routes
1707 if (route.isDefaultRoute()) {
1708 try {
1709 mNetd.removeRoute(interfaceName, route);
1710 } catch (Exception ex) {
1711 loge("error (" + ex + ") removing default route " + route);
1712 continue;
1713 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001714 if (DBG) {
1715 NetworkInfo networkInfo = nt.getNetworkInfo();
1716 log("removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1717 interfaceName + ")");
1718 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001719 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001720 }
1721 }
1722
1723 /**
1724 * Reads the network specific TCP buffer sizes from SystemProperties
1725 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1726 * wide use
1727 */
1728 public void updateNetworkSettings(NetworkStateTracker nt) {
1729 String key = nt.getTcpBufferSizesPropName();
1730 String bufferSizes = SystemProperties.get(key);
1731
1732 if (bufferSizes.length() == 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001733 loge(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001734
1735 // Setting to default values so we won't be stuck to previous values
1736 key = "net.tcp.buffersize.default";
1737 bufferSizes = SystemProperties.get(key);
1738 }
1739
1740 // Set values in kernel
1741 if (bufferSizes.length() != 0) {
1742 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001743 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001744 + "] which comes from [" + key + "]");
1745 }
1746 setBufferSize(bufferSizes);
1747 }
1748 }
1749
1750 /**
1751 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1752 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1753 *
1754 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1755 * writeMin, writeInitial, writeMax"
1756 */
1757 private void setBufferSize(String bufferSizes) {
1758 try {
1759 String[] values = bufferSizes.split(",");
1760
1761 if (values.length == 6) {
1762 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001763 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1764 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1765 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1766 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1767 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1768 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001769 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001770 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001771 }
1772 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001773 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001774 }
1775 }
1776
Robert Greenwalt2034b912009-08-12 16:08:25 -07001777 /**
1778 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1779 * on the highest priority active net which this process requested.
1780 * If there aren't any, clear it out
1781 */
1782 private void reassessPidDns(int myPid, boolean doBump)
1783 {
Wink Savillee70c6f52010-12-03 12:01:38 -08001784 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001785 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001786 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001787 continue;
1788 }
1789 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001790 if (nt.getNetworkInfo().isConnected() &&
1791 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001792 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001793 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001794 List pids = mNetRequestersPids[i];
1795 for (int j=0; j<pids.size(); j++) {
1796 Integer pid = (Integer)pids.get(j);
1797 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001798 Collection<InetAddress> dnses = p.getDnses();
1799 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001800 if (doBump) {
1801 bumpDns();
1802 }
1803 return;
1804 }
1805 }
1806 }
1807 }
1808 // nothing found - delete
1809 for (int i = 1; ; i++) {
1810 String prop = "net.dns" + i + "." + myPid;
1811 if (SystemProperties.get(prop).length() == 0) {
1812 if (doBump) {
1813 bumpDns();
1814 }
1815 return;
1816 }
1817 SystemProperties.set(prop, "");
1818 }
1819 }
1820
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001821 // return true if results in a change
1822 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001823 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001824 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001825 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001826 String dnsString = dns.getHostAddress();
1827 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1828 changed = true;
1829 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1830 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001831 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001832 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001833 }
1834
1835 private void bumpDns() {
1836 /*
1837 * Bump the property that tells the name resolver library to reread
1838 * the DNS server list from the properties.
1839 */
1840 String propVal = SystemProperties.get("net.dnschange");
1841 int n = 0;
1842 if (propVal.length() != 0) {
1843 try {
1844 n = Integer.parseInt(propVal);
1845 } catch (NumberFormatException e) {}
1846 }
1847 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001848 /*
1849 * Tell the VMs to toss their DNS caches
1850 */
1851 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1852 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08001853 /*
1854 * Connectivity events can happen before boot has completed ...
1855 */
1856 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07001857 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001858 }
1859
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001860 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001861 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001862 NetworkStateTracker nt = mNetTrackers[netType];
1863 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001864 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001865 if (p == null) return;
1866 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001867 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001868 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001869 int j = 1;
Robert Greenwalt94daa182010-09-01 11:34:05 -07001870 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001871 String dnsString = mDefaultDns.getHostAddress();
1872 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1873 if (DBG) {
1874 log("no dns provided - using " + dnsString);
1875 }
1876 changed = true;
1877 SystemProperties.set("net.dns1", dnsString);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001878 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001879 j++;
1880 } else {
1881 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001882 String dnsString = dns.getHostAddress();
1883 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1884 j++;
1885 continue;
1886 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001887 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001888 log("adding dns " + dns + " for " +
Robert Greenwalt94daa182010-09-01 11:34:05 -07001889 nt.getNetworkInfo().getTypeName());
1890 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001891 changed = true;
1892 SystemProperties.set("net.dns" + j++, dnsString);
Robert Greenwalt94daa182010-09-01 11:34:05 -07001893 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001894 }
1895 for (int k=j ; k<mNumDnsEntries; k++) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001896 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1897 if (DBG) log("erasing net.dns" + k);
1898 changed = true;
1899 SystemProperties.set("net.dns" + k, "");
1900 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001901 }
1902 mNumDnsEntries = j;
1903 } else {
1904 // set per-pid dns for attached secondary nets
1905 List pids = mNetRequestersPids[netType];
1906 for (int y=0; y< pids.size(); y++) {
1907 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001908 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001909 }
1910 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001911 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001912 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001913 }
1914
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001915 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001916 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1917 NETWORK_RESTORE_DELAY_PROP_NAME);
1918 if(restoreDefaultNetworkDelayStr != null &&
1919 restoreDefaultNetworkDelayStr.length() != 0) {
1920 try {
1921 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1922 } catch (NumberFormatException e) {
1923 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001924 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001925 // if the system property isn't set, use the value for the apn type
1926 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1927
1928 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1929 (mNetConfigs[networkType] != null)) {
1930 ret = mNetConfigs[networkType].restoreTime;
1931 }
1932 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001933 }
1934
1935 @Override
1936 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001937 if (mContext.checkCallingOrSelfPermission(
1938 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001939 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001940 pw.println("Permission Denial: can't dump ConnectivityService " +
1941 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1942 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001943 return;
1944 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001945 pw.println();
1946 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001947 if (nst != null) {
1948 if (nst.getNetworkInfo().isConnected()) {
1949 pw.println("Active network: " + nst.getNetworkInfo().
1950 getTypeName());
1951 }
1952 pw.println(nst.getNetworkInfo());
1953 pw.println(nst);
1954 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001955 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001956 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001957
1958 pw.println("Network Requester Pids:");
1959 for (int net : mPriorityList) {
1960 String pidString = net + ": ";
1961 for (Object pid : mNetRequestersPids[net]) {
1962 pidString = pidString + pid.toString() + ", ";
1963 }
1964 pw.println(pidString);
1965 }
1966 pw.println();
1967
1968 pw.println("FeatureUsers:");
1969 for (Object requester : mFeatureUsers) {
1970 pw.println(requester.toString());
1971 }
1972 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001973
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001974 synchronized (this) {
1975 pw.println("NetworkTranstionWakeLock is currently " +
1976 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1977 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1978 }
1979 pw.println();
1980
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001981 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07001982
1983 if (mInetLog != null) {
1984 pw.println();
1985 pw.println("Inet condition reports:");
1986 for(int i = 0; i < mInetLog.size(); i++) {
1987 pw.println(mInetLog.get(i));
1988 }
1989 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001990 }
1991
Robert Greenwalt2034b912009-08-12 16:08:25 -07001992 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001993 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07001994 public MyHandler(Looper looper) {
1995 super(looper);
1996 }
1997
The Android Open Source Project28527d22009-03-03 19:31:44 -08001998 @Override
1999 public void handleMessage(Message msg) {
2000 NetworkInfo info;
2001 switch (msg.what) {
2002 case NetworkStateTracker.EVENT_STATE_CHANGED:
2003 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002004 int type = info.getType();
2005 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002006
Wink Savillee70c6f52010-12-03 12:01:38 -08002007 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002008 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002009 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002010
2011 // Connectivity state changed:
2012 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002013 // [12-9] Network subtype (for mobile network, as defined
2014 // by TelephonyManager)
2015 // [8-3] Detailed state ordinal (as defined by
2016 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002017 // [2-0] Network type (as defined by ConnectivityManager)
2018 int eventLogParam = (info.getType() & 0x7) |
2019 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2020 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002021 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002022 eventLogParam);
2023
2024 if (info.getDetailedState() ==
2025 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002026 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002027 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002028 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002029 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002030 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002031 // the logic here is, handle SUSPENDED the same as
2032 // DISCONNECTED. The only difference being we are
2033 // broadcasting an intent with NetworkInfo that's
2034 // suspended. This allows the applications an
2035 // opportunity to handle DISCONNECTED and SUSPENDED
2036 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002037 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002038 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002039 handleConnect(info);
2040 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002041 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002042 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002043 info = (NetworkInfo) msg.obj;
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002044 handleConnectivityChange(info.getType(), true);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002045 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002046 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002047 String causedBy = null;
2048 synchronized (ConnectivityService.this) {
2049 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2050 mNetTransitionWakeLock.isHeld()) {
2051 mNetTransitionWakeLock.release();
2052 causedBy = mNetTransitionWakeLockCausedBy;
2053 }
2054 }
2055 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002056 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002057 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002058 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002059 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002060 FeatureUser u = (FeatureUser)msg.obj;
2061 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002062 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002063 case EVENT_INET_CONDITION_CHANGE:
2064 {
2065 int netType = msg.arg1;
2066 int condition = msg.arg2;
2067 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002068 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002069 }
2070 case EVENT_INET_CONDITION_HOLD_END:
2071 {
2072 int netType = msg.arg1;
2073 int sequence = msg.arg2;
2074 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002075 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002076 }
2077 case EVENT_SET_NETWORK_PREFERENCE:
2078 {
2079 int preference = msg.arg1;
2080 handleSetNetworkPreference(preference);
2081 break;
2082 }
2083 case EVENT_SET_BACKGROUND_DATA:
2084 {
2085 boolean enabled = (msg.arg1 == ENABLED);
2086 handleSetBackgroundData(enabled);
2087 break;
2088 }
2089 case EVENT_SET_MOBILE_DATA:
2090 {
2091 boolean enabled = (msg.arg1 == ENABLED);
2092 handleSetMobileData(enabled);
2093 break;
2094 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002095 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2096 {
2097 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002098 break;
2099 }
2100 case EVENT_SET_DEPENDENCY_MET:
2101 {
2102 boolean met = (msg.arg1 == ENABLED);
2103 handleSetDependencyMet(msg.arg2, met);
2104 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002105 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002106 }
2107 }
2108 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002109
2110 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002111 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002112 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002113
2114 if (isTetheringSupported()) {
2115 return mTethering.tether(iface);
2116 } else {
2117 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2118 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002119 }
2120
2121 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002122 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002123 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002124
2125 if (isTetheringSupported()) {
2126 return mTethering.untether(iface);
2127 } else {
2128 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2129 }
2130 }
2131
2132 // javadoc from interface
2133 public int getLastTetherError(String iface) {
2134 enforceTetherAccessPermission();
2135
2136 if (isTetheringSupported()) {
2137 return mTethering.getLastTetherError(iface);
2138 } else {
2139 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2140 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002141 }
2142
2143 // TODO - proper iface API for selection by property, inspection, etc
2144 public String[] getTetherableUsbRegexs() {
2145 enforceTetherAccessPermission();
2146 if (isTetheringSupported()) {
2147 return mTethering.getTetherableUsbRegexs();
2148 } else {
2149 return new String[0];
2150 }
2151 }
2152
2153 public String[] getTetherableWifiRegexs() {
2154 enforceTetherAccessPermission();
2155 if (isTetheringSupported()) {
2156 return mTethering.getTetherableWifiRegexs();
2157 } else {
2158 return new String[0];
2159 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002160 }
2161
Danica Chang96567052010-08-11 14:54:43 -07002162 public String[] getTetherableBluetoothRegexs() {
2163 enforceTetherAccessPermission();
2164 if (isTetheringSupported()) {
2165 return mTethering.getTetherableBluetoothRegexs();
2166 } else {
2167 return new String[0];
2168 }
2169 }
2170
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002171 // TODO - move iface listing, queries, etc to new module
2172 // javadoc from interface
2173 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002174 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002175 return mTethering.getTetherableIfaces();
2176 }
2177
2178 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002179 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002180 return mTethering.getTetheredIfaces();
2181 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002182
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002183 public String[] getTetheringErroredIfaces() {
2184 enforceTetherAccessPermission();
2185 return mTethering.getErroredIfaces();
2186 }
2187
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002188 // if ro.tether.denied = true we default to no tethering
2189 // gservices could set the secure setting to 1 though to enable it on a build where it
2190 // had previously been turned off.
2191 public boolean isTetheringSupported() {
2192 enforceTetherAccessPermission();
2193 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002194 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2195 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2196 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002197 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002198
2199 // An API NetworkStateTrackers can call when they lose their network.
2200 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2201 // whichever happens first. The timer is started by the first caller and not
2202 // restarted by subsequent callers.
2203 public void requestNetworkTransitionWakelock(String forWhom) {
2204 enforceConnectivityInternalPermission();
2205 synchronized (this) {
2206 if (mNetTransitionWakeLock.isHeld()) return;
2207 mNetTransitionWakeLockSerialNumber++;
2208 mNetTransitionWakeLock.acquire();
2209 mNetTransitionWakeLockCausedBy = forWhom;
2210 }
2211 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002212 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002213 mNetTransitionWakeLockSerialNumber, 0),
2214 mNetTransitionWakeLockTimeout);
2215 return;
2216 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002217
Robert Greenwalt986c7412010-09-08 15:24:47 -07002218 // 100 percent is full good, 0 is full bad.
2219 public void reportInetCondition(int networkType, int percentage) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002220 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002221 mContext.enforceCallingOrSelfPermission(
2222 android.Manifest.permission.STATUS_BAR,
2223 "ConnectivityService");
2224
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002225 if (DBG) {
2226 int pid = getCallingPid();
2227 int uid = getCallingUid();
2228 String s = pid + "(" + uid + ") reports inet is " +
2229 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2230 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2231 mInetLog.add(s);
2232 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2233 mInetLog.remove(0);
2234 }
2235 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002236 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002237 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2238 }
2239
2240 private void handleInetConditionChange(int netType, int condition) {
2241 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002242 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002243 netType + ", condition=" + condition +
2244 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2245 }
2246 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002247 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002248 return;
2249 }
2250 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002251 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002252 return;
2253 }
2254 mDefaultInetCondition = condition;
2255 int delay;
2256 if (mInetConditionChangeInFlight == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002257 if (DBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002258 // setup a new hold to debounce this
2259 if (mDefaultInetCondition > 50) {
2260 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2261 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2262 } else {
2263 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2264 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2265 }
2266 mInetConditionChangeInFlight = true;
2267 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2268 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2269 } else {
2270 // we've set the new condition, when this hold ends that will get
2271 // picked up
Wink Savillee70c6f52010-12-03 12:01:38 -08002272 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002273 }
2274 }
2275
2276 private void handleInetConditionHoldEnd(int netType, int sequence) {
2277 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002278 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002279 ", condition =" + mDefaultInetCondition +
2280 ", published condition =" + mDefaultInetConditionPublished);
2281 }
2282 mInetConditionChangeInFlight = false;
2283
2284 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002285 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002286 return;
2287 }
2288 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002289 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002290 return;
2291 }
2292 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002293 if (DBG) log("no change in condition - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002294 return;
2295 }
2296 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2297 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002298 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002299 return;
2300 }
2301 mDefaultInetConditionPublished = mDefaultInetCondition;
2302 sendInetConditionBroadcast(networkInfo);
2303 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002304 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002305
2306 public synchronized ProxyProperties getProxy() {
2307 if (mGlobalProxy != null) return mGlobalProxy;
2308 if (mDefaultProxy != null) return mDefaultProxy;
2309 return null;
2310 }
2311
2312 public void setGlobalProxy(ProxyProperties proxyProperties) {
2313 enforceChangePermission();
2314 synchronized (mGlobalProxyLock) {
2315 if (proxyProperties == mGlobalProxy) return;
2316 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2317 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2318
2319 String host = "";
2320 int port = 0;
2321 String exclList = "";
2322 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2323 mGlobalProxy = new ProxyProperties(proxyProperties);
2324 host = mGlobalProxy.getHost();
2325 port = mGlobalProxy.getPort();
2326 exclList = mGlobalProxy.getExclusionList();
2327 } else {
2328 mGlobalProxy = null;
2329 }
2330 ContentResolver res = mContext.getContentResolver();
2331 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2332 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002333 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002334 exclList);
2335 }
2336
2337 if (mGlobalProxy == null) {
2338 proxyProperties = mDefaultProxy;
2339 }
2340 sendProxyBroadcast(proxyProperties);
2341 }
2342
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002343 private void loadGlobalProxy() {
2344 ContentResolver res = mContext.getContentResolver();
2345 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2346 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2347 String exclList = Settings.Secure.getString(res,
2348 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2349 if (!TextUtils.isEmpty(host)) {
2350 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2351 synchronized (mGlobalProxyLock) {
2352 mGlobalProxy = proxyProperties;
2353 }
2354 }
2355 }
2356
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002357 public ProxyProperties getGlobalProxy() {
2358 synchronized (mGlobalProxyLock) {
2359 return mGlobalProxy;
2360 }
2361 }
2362
2363 private void handleApplyDefaultProxy(int type) {
2364 // check if new default - push it out to all VM if so
2365 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2366 synchronized (this) {
2367 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2368 if (mDefaultProxy == proxy) return;
2369 if (!TextUtils.isEmpty(proxy.getHost())) {
2370 mDefaultProxy = proxy;
2371 } else {
2372 mDefaultProxy = null;
2373 }
2374 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002375 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002376 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2377 if (mGlobalProxy != null) return;
2378 sendProxyBroadcast(proxy);
2379 }
2380
2381 private void handleDeprecatedGlobalHttpProxy() {
2382 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2383 Settings.Secure.HTTP_PROXY);
2384 if (!TextUtils.isEmpty(proxy)) {
2385 String data[] = proxy.split(":");
2386 String proxyHost = data[0];
2387 int proxyPort = 8080;
2388 if (data.length > 1) {
2389 try {
2390 proxyPort = Integer.parseInt(data[1]);
2391 } catch (NumberFormatException e) {
2392 return;
2393 }
2394 }
2395 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2396 setGlobalProxy(p);
2397 }
2398 }
2399
2400 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002401 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savillee70c6f52010-12-03 12:01:38 -08002402 log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002403 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002404 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2405 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002406 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002407 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002408 }
2409
2410 private static class SettingsObserver extends ContentObserver {
2411 private int mWhat;
2412 private Handler mHandler;
2413 SettingsObserver(Handler handler, int what) {
2414 super(handler);
2415 mHandler = handler;
2416 mWhat = what;
2417 }
2418
2419 void observe(Context context) {
2420 ContentResolver resolver = context.getContentResolver();
2421 resolver.registerContentObserver(Settings.Secure.getUriFor(
2422 Settings.Secure.HTTP_PROXY), false, this);
2423 }
2424
2425 @Override
2426 public void onChange(boolean selfChange) {
2427 mHandler.obtainMessage(mWhat).sendToTarget();
2428 }
2429 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002430
2431 private void log(String s) {
2432 Slog.d(TAG, s);
2433 }
2434
2435 private void loge(String s) {
2436 Slog.e(TAG, s);
2437 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002438
Wink Savillef6b76692011-02-24 17:58:51 -08002439 int convertFeatureToNetworkType(String feature){
2440 int networkType = -1;
2441 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2442 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2443 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2444 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2445 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2446 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2447 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2448 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2449 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2450 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2451 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2452 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2453 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2454 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2455 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2456 }
2457 return networkType;
2458 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002459
2460 private static <T> T checkNotNull(T value, String message) {
2461 if (value == null) {
2462 throw new NullPointerException(message);
2463 }
2464 return value;
2465 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002466
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002467 /**
2468 * Protect a socket from VPN routing rules. This method is used by
2469 * VpnBuilder and not available in ConnectivityManager. Permission
2470 * checks are done in Vpn class.
2471 * @hide
2472 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002473 @Override
2474 public void protectVpn(ParcelFileDescriptor socket) {
2475 mVpn.protect(socket, getDefaultInterface());
2476 }
2477
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002478 /**
2479 * Prepare for a VPN application. This method is used by VpnDialogs
2480 * and not available in ConnectivityManager. Permission checks are
2481 * done in Vpn class.
2482 * @hide
2483 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002484 @Override
2485 public String prepareVpn(String packageName) {
2486 return mVpn.prepare(packageName);
2487 }
2488
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002489 /**
2490 * Configure a TUN interface and return its file descriptor. Parameters
2491 * are encoded and opaque to this class. This method is used by VpnBuilder
2492 * and not available in ConnectivityManager. Permission checks are done
2493 * in Vpn class.
2494 * @hide
2495 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002496 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002497 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002498 return mVpn.establish(config);
2499 }
2500
2501 private String getDefaultInterface() {
2502 if (ConnectivityManager.isNetworkTypeValid(mActiveDefaultNetwork)) {
2503 NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
2504 if (tracker != null) {
2505 LinkProperties properties = tracker.getLinkProperties();
2506 if (properties != null) {
2507 return properties.getInterfaceName();
2508 }
2509 }
2510 }
2511 throw new IllegalStateException("No default interface");
2512 }
2513
2514 /**
2515 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2516 * through NetworkStateTracker since it works differently. For example, it
2517 * needs to override DNS servers but never takes the default routes. It
2518 * relies on another data network, and it could keep existing connections
2519 * alive after reconnecting, switching between networks, or even resuming
2520 * from deep sleep. Calls from applications should be done synchronously
2521 * to avoid race conditions. As these are all hidden APIs, refactoring can
2522 * be done whenever a better abstraction is developed.
2523 */
2524 public class VpnCallback {
2525
2526 private VpnCallback() {
2527 }
2528
2529 public synchronized void override(String[] dnsServers) {
2530 // TODO: override DNS servers and http proxy.
2531 }
2532
2533 public synchronized void restore() {
2534 // TODO: restore VPN changes.
2535 }
2536 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002537}