blob: 8ac8f2bc4717575014c015dda5290178574b5a17 [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
Robert Greenwalt2034b912009-08-12 16:08:25 -0700134 // priority order of the nettrackers
135 // (excluding dynamically set mNetworkPreference)
136 // TODO - move mNetworkTypePreference into this
137 private int[] mPriorityList;
138
The Android Open Source Project28527d22009-03-03 19:31:44 -0800139 private Context mContext;
140 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700141 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700142 // 0 is full bad, 100 is full good
143 private int mDefaultInetCondition = 0;
144 private int mDefaultInetConditionPublished = 0;
145 private boolean mInetConditionChangeInFlight = false;
146 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800147
148 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800149
150 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700151 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800152
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800153 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
154
Robert Greenwalt355205c2011-05-10 15:05:02 -0700155 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700156 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700157
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700158 private static final int ENABLED = 1;
159 private static final int DISABLED = 0;
160
161 // Share the event space with NetworkStateTracker (which can't see this
162 // internal class but sends us events). If you change these, change
163 // NetworkStateTracker.java too.
164 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
165 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
166
167 /**
168 * used internally as a delayed event to make us switch back to the
169 * default network
170 */
171 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
172 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
173
174 /**
175 * used internally to change our mobile data enabled flag
176 */
177 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
178 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
179
180 /**
181 * used internally to change our network preference setting
182 * arg1 = networkType to prefer
183 */
184 private static final int EVENT_SET_NETWORK_PREFERENCE =
185 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
186
187 /**
188 * used internally to synchronize inet condition reports
189 * arg1 = networkType
190 * arg2 = condition (0 bad, 100 good)
191 */
192 private static final int EVENT_INET_CONDITION_CHANGE =
193 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
194
195 /**
196 * used internally to mark the end of inet condition hold periods
197 * arg1 = networkType
198 */
199 private static final int EVENT_INET_CONDITION_HOLD_END =
200 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
201
202 /**
203 * used internally to set the background data preference
204 * arg1 = TRUE for enabled, FALSE for disabled
205 */
206 private static final int EVENT_SET_BACKGROUND_DATA =
207 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
208
209 /**
210 * used internally to set enable/disable cellular data
211 * arg1 = ENBALED or DISABLED
212 */
213 private static final int EVENT_SET_MOBILE_DATA =
214 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
215
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700216 /**
217 * used internally to clear a wakelock when transitioning
218 * from one net to another
219 */
220 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
221 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
222
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700223 /**
224 * used internally to reload global proxy settings
225 */
226 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
227 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
228
Robert Greenwalt34848c02011-03-25 13:09:25 -0700229 /**
230 * used internally to set external dependency met/unmet
231 * arg1 = ENABLED (met) or DISABLED (unmet)
232 * arg2 = NetworkType
233 */
234 private static final int EVENT_SET_DEPENDENCY_MET =
235 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
236
Robert Greenwalt2034b912009-08-12 16:08:25 -0700237 private Handler mHandler;
238
239 // list of DeathRecipients used to make sure features are turned off when
240 // a process dies
241 private List mFeatureUsers;
242
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400243 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800244 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400245
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700246 private PowerManager.WakeLock mNetTransitionWakeLock;
247 private String mNetTransitionWakeLockCausedBy = "";
248 private int mNetTransitionWakeLockSerialNumber;
249 private int mNetTransitionWakeLockTimeout;
250
Robert Greenwalt94daa182010-09-01 11:34:05 -0700251 private InetAddress mDefaultDns;
252
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700253 // used in DBG mode to track inet condition reports
254 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
255 private ArrayList mInetLog;
256
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700257 // track the current default http proxy - tell the world if we get a new one (real change)
258 private ProxyProperties mDefaultProxy = null;
259 // track the global proxy.
260 private ProxyProperties mGlobalProxy = null;
261 private final Object mGlobalProxyLock = new Object();
262
263 private SettingsObserver mSettingsObserver;
264
Robert Greenwalt34848c02011-03-25 13:09:25 -0700265 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700266 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700267
Robert Greenwalt12c44552009-12-07 11:33:18 -0800268 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700269 public int mSimultaneity;
270 public int mType;
271 public RadioAttributes(String init) {
272 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700273 mType = Integer.parseInt(fragments[0]);
274 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700275 }
276 }
277 RadioAttributes[] mRadioAttributes;
278
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700279 // the set of network types that can only be enabled by system/sig apps
280 List mProtectedNetworks;
281
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700282 public ConnectivityService(
283 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800284 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800285
Wink Saville775aad62010-09-02 19:23:52 -0700286 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
287 handlerThread.start();
288 mHandler = new MyHandler(handlerThread.getLooper());
289
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800290 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
291 Settings.Secure.BACKGROUND_DATA, 1) == 1);
292
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800293 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800294 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
295 String id = Settings.Secure.getString(context.getContentResolver(),
296 Settings.Secure.ANDROID_ID);
297 if (id != null && id.length() > 0) {
298 String name = new String("android_").concat(id);
299 SystemProperties.set("net.hostname", name);
300 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800301 }
302
Robert Greenwalt94daa182010-09-01 11:34:05 -0700303 // read our default dns server ip
304 String dns = Settings.Secure.getString(context.getContentResolver(),
305 Settings.Secure.DEFAULT_DNS_SERVER);
306 if (dns == null || dns.length() == 0) {
307 dns = context.getResources().getString(
308 com.android.internal.R.string.config_default_dns_server);
309 }
310 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800311 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
312 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800313 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700314 }
315
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700316 mContext = checkNotNull(context, "missing Context");
317 mNetd = checkNotNull(netd, "missing INetworkManagementService");
318 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700319
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700320 try {
321 mPolicyManager.registerListener(mPolicyListener);
322 } catch (RemoteException e) {
323 // ouch, no rules updates means some processes may never get network
324 Slog.e(TAG, "unable to register INetworkPolicyListener", e);
325 }
326
327 final PowerManager powerManager = (PowerManager) context.getSystemService(
328 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700329 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
330 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
331 com.android.internal.R.integer.config_networkTransitionTimeout);
332
Robert Greenwalt2034b912009-08-12 16:08:25 -0700333 mNetTrackers = new NetworkStateTracker[
334 ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700335
The Android Open Source Project28527d22009-03-03 19:31:44 -0800336 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700337
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700338 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700339 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700340
Robert Greenwalt2034b912009-08-12 16:08:25 -0700341 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700342 String[] raStrings = context.getResources().getStringArray(
343 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700344 for (String raString : raStrings) {
345 RadioAttributes r = new RadioAttributes(raString);
346 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800347 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700348 continue;
349 }
350 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800351 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700352 r.mType);
353 continue;
354 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700355 mRadioAttributes[r.mType] = r;
356 }
357
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700358 String[] naStrings = context.getResources().getStringArray(
359 com.android.internal.R.array.networkAttributes);
360 for (String naString : naStrings) {
361 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700362 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700363 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800364 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700365 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700366 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700367 }
Wink Savillef2a62832011-04-07 14:23:45 -0700368 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800369 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700370 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700371 continue;
372 }
Wink Savillef2a62832011-04-07 14:23:45 -0700373 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800374 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700375 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700376 continue;
377 }
Wink Savillef2a62832011-04-07 14:23:45 -0700378 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700379 mNetworksDefined++;
380 } catch(Exception e) {
381 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700382 }
383 }
384
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700385 mProtectedNetworks = new ArrayList<Integer>();
386 int[] protectedNetworks = context.getResources().getIntArray(
387 com.android.internal.R.array.config_protectedNetworks);
388 for (int p : protectedNetworks) {
389 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
390 mProtectedNetworks.add(p);
391 } else {
392 if (DBG) loge("Ignoring protectedNetwork " + p);
393 }
394 }
395
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700396 // high priority first
397 mPriorityList = new int[mNetworksDefined];
398 {
399 int insertionPoint = mNetworksDefined-1;
400 int currentLowest = 0;
401 int nextLowest = 0;
402 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700403 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700404 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700405 if (na.priority < currentLowest) continue;
406 if (na.priority > currentLowest) {
407 if (na.priority < nextLowest || nextLowest == 0) {
408 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700409 }
410 continue;
411 }
Wink Savillef2a62832011-04-07 14:23:45 -0700412 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700413 }
414 currentLowest = nextLowest;
415 nextLowest = 0;
416 }
417 }
418
419 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
420 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700421 mNetRequestersPids[i] = new ArrayList();
422 }
423
424 mFeatureUsers = new ArrayList();
425
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700426 mNumDnsEntries = 0;
427
428 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
429 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800430 /*
431 * Create the network state trackers for Wi-Fi and mobile
432 * data. Maybe this could be done with a factory class,
433 * but it's not clear that it's worth it, given that
434 * the number of different network types is not going
435 * to change very often.
436 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700437 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700438 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700439 case ConnectivityManager.TYPE_WIFI:
Wink Savillee70c6f52010-12-03 12:01:38 -0800440 if (DBG) log("Starting Wifi Service.");
Wink Saville7fabfa22010-08-13 16:11:42 -0700441 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff25be0762010-07-28 09:35:20 -0700442 WifiService wifiService = new WifiService(context);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700443 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff25be0762010-07-28 09:35:20 -0700444 wifiService.checkAndStartWifi();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700445 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Saville7fabfa22010-08-13 16:11:42 -0700446 wst.startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700447 break;
448 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700449 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700450 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700451 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700452 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800453 case ConnectivityManager.TYPE_DUMMY:
454 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700455 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800456 mNetTrackers[netType].startMonitoring(context, mHandler);
457 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800458 case ConnectivityManager.TYPE_BLUETOOTH:
459 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
460 mNetTrackers[netType].startMonitoring(context, mHandler);
461 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800462 case ConnectivityManager.TYPE_ETHERNET:
463 mNetTrackers[netType] = EthernetDataTracker.getInstance();
464 mNetTrackers[netType].startMonitoring(context, mHandler);
465 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700466 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800467 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700468 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700469 continue;
470 }
471 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800472
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700473 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
474 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
475
476 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700477 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700478 mTethering.getTetherableWifiRegexs().length != 0 ||
479 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700480 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800481
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700482 mVpn = new Vpn(mContext, new VpnCallback());
483
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700484 try {
485 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700486 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700487 } catch (RemoteException e) {
488 loge("Error registering observer :" + e);
489 }
490
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700491 if (DBG) {
492 mInetLog = new ArrayList();
493 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700494
495 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
496 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800497
498 loadGlobalProxy();
Hung-ying Tyan4e723422011-01-19 16:48:38 +0800499
500 VpnManager.startVpnService(context);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800501 }
502
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700503
The Android Open Source Project28527d22009-03-03 19:31:44 -0800504 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700505 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800506 * @param preference the new preference
507 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700508 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800509 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700510
511 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800512 }
513
514 public int getNetworkPreference() {
515 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700516 int preference;
517 synchronized(this) {
518 preference = mNetworkPreference;
519 }
520 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800521 }
522
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700523 private void handleSetNetworkPreference(int preference) {
524 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700525 mNetConfigs[preference] != null &&
526 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700527 if (mNetworkPreference != preference) {
528 final ContentResolver cr = mContext.getContentResolver();
529 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
530 synchronized(this) {
531 mNetworkPreference = preference;
532 }
533 enforcePreference();
534 }
535 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800536 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700537
The Android Open Source Project28527d22009-03-03 19:31:44 -0800538 private int getPersistedNetworkPreference() {
539 final ContentResolver cr = mContext.getContentResolver();
540
541 final int networkPrefSetting = Settings.Secure
542 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
543 if (networkPrefSetting != -1) {
544 return networkPrefSetting;
545 }
546
547 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
548 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700549
The Android Open Source Project28527d22009-03-03 19:31:44 -0800550 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700551 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800552 * In this method, we only tear down a non-preferred network. Establishing
553 * a connection to the preferred network is taken care of when we handle
554 * the disconnect event from the non-preferred network
555 * (see {@link #handleDisconnect(NetworkInfo)}).
556 */
557 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700558 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800559 return;
560
Robert Greenwalt2034b912009-08-12 16:08:25 -0700561 if (!mNetTrackers[mNetworkPreference].isAvailable())
562 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800563
Robert Greenwalt2034b912009-08-12 16:08:25 -0700564 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700565 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700566 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700567 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800568 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700569 " in enforcePreference");
570 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700571 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800572 }
573 }
574 }
575
576 private boolean teardown(NetworkStateTracker netTracker) {
577 if (netTracker.teardown()) {
578 netTracker.setTeardownRequested(true);
579 return true;
580 } else {
581 return false;
582 }
583 }
584
585 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700586 * Check if UID should be blocked from using the network represented by the
587 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700588 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700589 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
590 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700591
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700592 final boolean networkCostly;
593 final int uidRules;
594 synchronized (mRulesLock) {
595 networkCostly = mMeteredIfaces.contains(iface);
596 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700597 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700598
599 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
600 return true;
601 }
602
603 // no restrictive rules; network is visible
604 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700605 }
606
607 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700608 * Return a filtered {@link NetworkInfo}, potentially marked
609 * {@link DetailedState#BLOCKED} based on
610 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700611 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700612 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
613 NetworkInfo info = tracker.getNetworkInfo();
614 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700615 // network is blocked; clone and override state
616 info = new NetworkInfo(info);
617 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700618 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700619 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700620 }
621
622 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800623 * Return NetworkInfo for the active (i.e., connected) network interface.
624 * It is assumed that at most one network is active at a time. If more
625 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700626 * @return the info for the active network, or {@code null} if none is
627 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800628 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700629 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800630 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700631 enforceAccessPermission();
632 final int uid = Binder.getCallingUid();
633 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800634 }
635
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700636 @Override
637 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
638 enforceConnectivityInternalPermission();
639 return getNetworkInfo(mActiveDefaultNetwork, uid);
640 }
641
642 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800643 public NetworkInfo getNetworkInfo(int networkType) {
644 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700645 final int uid = Binder.getCallingUid();
646 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800647 }
648
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700649 private NetworkInfo getNetworkInfo(int networkType, int uid) {
650 NetworkInfo info = null;
651 if (isNetworkTypeValid(networkType)) {
652 final NetworkStateTracker tracker = mNetTrackers[networkType];
653 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700654 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700655 }
656 }
657 return info;
658 }
659
660 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800661 public NetworkInfo[] getAllNetworkInfo() {
662 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700663 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700664 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700665 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700666 for (NetworkStateTracker tracker : mNetTrackers) {
667 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700668 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700669 }
670 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800671 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700672 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800673 }
674
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700675 /**
676 * Return LinkProperties for the active (i.e., connected) default
677 * network interface. It is assumed that at most one default network
678 * is active at a time. If more than one is active, it is indeterminate
679 * which will be returned.
680 * @return the ip properties for the active network, or {@code null} if
681 * none is active
682 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700683 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700684 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700685 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700686 }
687
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700688 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700689 public LinkProperties getLinkProperties(int networkType) {
690 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700691 if (isNetworkTypeValid(networkType)) {
692 final NetworkStateTracker tracker = mNetTrackers[networkType];
693 if (tracker != null) {
694 return tracker.getLinkProperties();
695 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700696 }
697 return null;
698 }
699
Jeff Sharkey21062e72011-05-28 20:56:34 -0700700 @Override
701 public NetworkState[] getAllNetworkState() {
702 enforceAccessPermission();
703 final int uid = Binder.getCallingUid();
704 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700705 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700706 for (NetworkStateTracker tracker : mNetTrackers) {
707 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700708 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700709 result.add(new NetworkState(
710 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
711 }
712 }
713 }
714 return result.toArray(new NetworkState[result.size()]);
715 }
716
The Android Open Source Project28527d22009-03-03 19:31:44 -0800717 public boolean setRadios(boolean turnOn) {
718 boolean result = true;
719 enforceChangePermission();
720 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700721 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800722 }
723 return result;
724 }
725
726 public boolean setRadio(int netType, boolean turnOn) {
727 enforceChangePermission();
728 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
729 return false;
730 }
731 NetworkStateTracker tracker = mNetTrackers[netType];
732 return tracker != null && tracker.setRadio(turnOn);
733 }
734
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700735 /**
736 * Used to notice when the calling process dies so we can self-expire
737 *
738 * Also used to know if the process has cleaned up after itself when
739 * our auto-expire timer goes off. The timer has a link to an object.
740 *
741 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700742 private class FeatureUser implements IBinder.DeathRecipient {
743 int mNetworkType;
744 String mFeature;
745 IBinder mBinder;
746 int mPid;
747 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800748 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700749
750 FeatureUser(int type, String feature, IBinder binder) {
751 super();
752 mNetworkType = type;
753 mFeature = feature;
754 mBinder = binder;
755 mPid = getCallingPid();
756 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800757 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700758
Robert Greenwalt2034b912009-08-12 16:08:25 -0700759 try {
760 mBinder.linkToDeath(this, 0);
761 } catch (RemoteException e) {
762 binderDied();
763 }
764 }
765
766 void unlinkDeathRecipient() {
767 mBinder.unlinkToDeath(this, 0);
768 }
769
770 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800771 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800772 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
773 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700774 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700775 }
776
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700777 public void expire() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800778 log("ConnectivityService FeatureUser expire(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800779 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
780 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700781 stopUsingNetworkFeature(this, false);
782 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800783
784 public String toString() {
785 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
786 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
787 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700788 }
789
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700790 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700791 public int startUsingNetworkFeature(int networkType, String feature,
792 IBinder binder) {
793 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800794 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700795 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800796 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700797 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700798 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700799 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800800 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700801
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700802 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700803
804 // TODO - move this into the MobileDataStateTracker
805 int usedNetworkType = networkType;
806 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800807 usedNetworkType = convertFeatureToNetworkType(feature);
808 if (usedNetworkType < 0) {
809 Slog.e(TAG, "Can't match any netTracker!");
810 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700811 }
812 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700813
814 if (mProtectedNetworks.contains(usedNetworkType)) {
815 enforceConnectivityInternalPermission();
816 }
817
Robert Greenwalt2034b912009-08-12 16:08:25 -0700818 NetworkStateTracker network = mNetTrackers[usedNetworkType];
819 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800820 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700821 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700822 NetworkStateTracker radio = mNetTrackers[networkType];
823 NetworkInfo ni = network.getNetworkInfo();
824
825 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800826 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800827 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
828 return Phone.APN_TYPE_NOT_AVAILABLE;
829 } else {
830 // else make the attempt anyway - probably giving REQUEST_STARTED below
831 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700832 }
833
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700834 synchronized(this) {
835 mFeatureUsers.add(f);
836 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
837 // this gets used for per-pid dns when connected
838 mNetRequestersPids[usedNetworkType].add(currentPid);
839 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700840 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700841
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700842 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
843
844 if (restoreTimer >= 0) {
845 mHandler.sendMessageDelayed(
846 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
847 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700848
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700849 if ((ni.isConnectedOrConnecting() == true) &&
850 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700851 if (ni.isConnected() == true) {
852 // add the pid-specific dns
Robert Greenwalt3afbead2010-07-23 15:46:26 -0700853 handleDnsConfigurationChange(networkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800854 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700855 return Phone.APN_ALREADY_ACTIVE;
856 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800857 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700858 return Phone.APN_REQUEST_STARTED;
859 }
860
861 // check if the radio in play can make another contact
862 // assume if cannot for now
863
Wink Savillee70c6f52010-12-03 12:01:38 -0800864 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700865 network.reconnect();
866 return Phone.APN_REQUEST_STARTED;
867 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800868 // need to remember this unsupported request so we respond appropriately on stop
869 synchronized(this) {
870 mFeatureUsers.add(f);
871 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
872 // this gets used for per-pid dns when connected
873 mNetRequestersPids[usedNetworkType].add(currentPid);
874 }
875 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700876 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700877 }
878 }
879 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800880 }
881
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700882 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800883 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700884 enforceChangePermission();
885
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700886 int pid = getCallingPid();
887 int uid = getCallingUid();
888
889 FeatureUser u = null;
890 boolean found = false;
891
892 synchronized(this) {
893 for (int i = 0; i < mFeatureUsers.size() ; i++) {
894 u = (FeatureUser)mFeatureUsers.get(i);
895 if (uid == u.mUid && pid == u.mPid &&
896 networkType == u.mNetworkType &&
897 TextUtils.equals(feature, u.mFeature)) {
898 found = true;
899 break;
900 }
901 }
902 }
903 if (found && u != null) {
904 // stop regardless of how many other time this proc had called start
905 return stopUsingNetworkFeature(u, true);
906 } else {
907 // none found!
Wink Savillee70c6f52010-12-03 12:01:38 -0800908 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700909 return 1;
910 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700911 }
912
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700913 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
914 int networkType = u.mNetworkType;
915 String feature = u.mFeature;
916 int pid = u.mPid;
917 int uid = u.mUid;
918
919 NetworkStateTracker tracker = null;
920 boolean callTeardown = false; // used to carry our decision outside of sync block
921
Robert Greenwalt2034b912009-08-12 16:08:25 -0700922 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800923 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700924 ": " + feature);
925 }
Robert Greenwalt28f43012009-10-06 17:52:40 -0700926
The Android Open Source Project28527d22009-03-03 19:31:44 -0800927 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
928 return -1;
929 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700930
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700931 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
932 // sync block
933 synchronized(this) {
934 // check if this process still has an outstanding start request
935 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800936 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700937 return 1;
938 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700939 u.unlinkDeathRecipient();
940 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
941 // If we care about duplicate requests, check for that here.
942 //
943 // This is done to support the extension of a request - the app
944 // can request we start the network feature again and renew the
945 // auto-shutoff delay. Normal "stop" calls from the app though
946 // do not pay attention to duplicate requests - in effect the
947 // API does not refcount and a single stop will counter multiple starts.
948 if (ignoreDups == false) {
949 for (int i = 0; i < mFeatureUsers.size() ; i++) {
950 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
951 if (x.mUid == u.mUid && x.mPid == u.mPid &&
952 x.mNetworkType == u.mNetworkType &&
953 TextUtils.equals(x.mFeature, u.mFeature)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800954 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700955 return 1;
956 }
957 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700958 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700959
960 // TODO - move to MobileDataStateTracker
961 int usedNetworkType = networkType;
962 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800963 usedNetworkType = convertFeatureToNetworkType(feature);
964 if (usedNetworkType < 0) {
965 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700966 }
967 }
968 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700969 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800970 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700971 return -1;
972 }
973 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700974 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700975 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -0800976 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700977 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800978 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700979 "others still using it");
980 return 1;
981 }
982 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -0800983 } else {
984 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700985 }
986 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800987 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700988 if (callTeardown) {
989 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700990 return 1;
991 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -0700992 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700993 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800994 }
995
996 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700997 * @deprecated use requestRouteToHostAddress instead
998 *
The Android Open Source Project28527d22009-03-03 19:31:44 -0800999 * Ensure that a network route exists to deliver traffic to the specified
1000 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001001 * @param networkType the type of the network over which traffic to the
1002 * specified host is to be routed
1003 * @param hostAddress the IP address of the host to which the route is
1004 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001005 * @return {@code true} on success, {@code false} on failure
1006 */
1007 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001008 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1009
1010 if (inetAddress == null) {
1011 return false;
1012 }
1013
1014 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1015 }
1016
1017 /**
1018 * Ensure that a network route exists to deliver traffic to the specified
1019 * host via the specified network interface.
1020 * @param networkType the type of the network over which traffic to the
1021 * specified host is to be routed
1022 * @param hostAddress the IP address of the host to which the route is
1023 * desired
1024 * @return {@code true} on success, {@code false} on failure
1025 */
1026 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001027 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001028 if (mProtectedNetworks.contains(networkType)) {
1029 enforceConnectivityInternalPermission();
1030 }
1031
The Android Open Source Project28527d22009-03-03 19:31:44 -08001032 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1033 return false;
1034 }
1035 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001036
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001037 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1038 tracker.isTeardownRequested()) {
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001039 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001040 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001041 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001042 }
1043 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001044 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001045 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001046 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001047 return addHostRoute(tracker, addr, 0);
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001048 } catch (UnknownHostException e) {}
1049 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001050 }
1051
1052 /**
1053 * Ensure that a network route exists to deliver traffic to the specified
1054 * host via the mobile data network.
1055 * @param hostAddress the IP address of the host to which the route is desired,
1056 * in network byte order.
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001057 * TODO - deprecate
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001058 * @return {@code true} on success, {@code false} on failure
1059 */
Robert Greenwaltbd492212011-05-06 17:10:53 -07001060 private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress, int cycleCount) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001061 LinkProperties lp = nt.getLinkProperties();
1062 if ((lp == null) || (hostAddress == null)) return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001063
Robert Greenwaltbd492212011-05-06 17:10:53 -07001064 String interfaceName = lp.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001065 if (DBG) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001066 log("Requested host route to " + hostAddress + "(" + interfaceName + "), cycleCount=" +
1067 cycleCount);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001068 }
Robert Greenwaltbd492212011-05-06 17:10:53 -07001069 if (interfaceName == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001070 if (DBG) loge("addHostRoute failed due to null interface name");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001071 return false;
1072 }
Robert Greenwaltbd492212011-05-06 17:10:53 -07001073
1074 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), hostAddress);
Robert Greenwalt355205c2011-05-10 15:05:02 -07001075 InetAddress gatewayAddress = null;
Robert Greenwaltbd492212011-05-06 17:10:53 -07001076 if (bestRoute != null) {
Robert Greenwalt355205c2011-05-10 15:05:02 -07001077 gatewayAddress = bestRoute.getGateway();
Robert Greenwaltbd492212011-05-06 17:10:53 -07001078 // if the best route is ourself, don't relf-reference, just add the host route
Robert Greenwalt355205c2011-05-10 15:05:02 -07001079 if (hostAddress.equals(gatewayAddress)) gatewayAddress = null;
Robert Greenwaltbd492212011-05-06 17:10:53 -07001080 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001081 if (gatewayAddress != null) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001082 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1083 loge("Error adding hostroute - too much recursion");
1084 return false;
1085 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001086 if (!addHostRoute(nt, gatewayAddress, cycleCount+1)) return false;
Robert Greenwaltbd492212011-05-06 17:10:53 -07001087 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001088
1089 RouteInfo route = RouteInfo.makeHostRoute(hostAddress, gatewayAddress);
1090
1091 try {
1092 mNetd.addRoute(interfaceName, route);
1093 return true;
1094 } catch (Exception ex) {
1095 return false;
1096 }
Robert Greenwaltbd492212011-05-06 17:10:53 -07001097 }
1098
1099 // TODO support the removal of single host routes. Keep a ref count of them so we
1100 // aren't over-zealous
1101 private boolean removeHostRoute(NetworkStateTracker nt, InetAddress hostAddress) {
1102 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001103 }
1104
1105 /**
1106 * @see ConnectivityManager#getBackgroundDataSetting()
1107 */
1108 public boolean getBackgroundDataSetting() {
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001109 return mBackgroundDataEnabled.get();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001110 }
Robert Greenwalt0659da32009-07-16 17:21:39 -07001111
The Android Open Source Project28527d22009-03-03 19:31:44 -08001112 /**
1113 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1114 */
1115 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1116 mContext.enforceCallingOrSelfPermission(
1117 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1118 "ConnectivityService");
Robert Greenwalt0659da32009-07-16 17:21:39 -07001119
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001120 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1121
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001122 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1123 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1124 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001125
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001126 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwalt0ffdef12011-02-25 13:44:09 -08001127 Settings.Secure.putInt(mContext.getContentResolver(),
1128 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1129 Intent broadcast = new Intent(
1130 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1131 mContext.sendBroadcast(broadcast);
Robert Greenwalt0659da32009-07-16 17:21:39 -07001132 }
1133
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001134 /**
1135 * @see ConnectivityManager#getMobileDataEnabled()
1136 */
1137 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001138 // TODO: This detail should probably be in DataConnectionTracker's
1139 // which is where we store the value and maybe make this
1140 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001141 enforceAccessPermission();
1142 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1143 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savillee70c6f52010-12-03 12:01:38 -08001144 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001145 return retVal;
1146 }
1147
Robert Greenwalt34848c02011-03-25 13:09:25 -07001148 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001149 enforceConnectivityInternalPermission();
1150
Robert Greenwalt34848c02011-03-25 13:09:25 -07001151 if (DBG) {
1152 log("setDataDependency(" + networkType + ", " + met + ")");
1153 }
1154 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1155 (met ? ENABLED : DISABLED), networkType));
1156 }
1157
1158 private void handleSetDependencyMet(int networkType, boolean met) {
1159 if (mNetTrackers[networkType] != null) {
1160 if (DBG) {
1161 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1162 }
1163 mNetTrackers[networkType].setDependencyMet(met);
1164 }
1165 }
1166
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001167 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1168 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001169 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001170 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001171 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001172
1173 if (LOGD_RULES) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001174 Slog.d(TAG, "onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001175 }
1176
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001177 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001178 // skip update when we've already applied rules
1179 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1180 if (oldRules == uidRules) return;
1181
1182 mUidRules.put(uid, uidRules);
1183 }
1184
1185 // TODO: dispatch into NMS to push rules towards kernel module
1186 // TODO: notify UID when it has requested targeted updates
1187 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001188
1189 @Override
1190 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1191 // only someone like NPMS should only be calling us
1192 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1193
1194 if (LOGD_RULES) {
1195 Slog.d(TAG,
1196 "onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1197 }
1198
1199 synchronized (mRulesLock) {
1200 mMeteredIfaces.clear();
1201 for (String iface : meteredIfaces) {
1202 mMeteredIfaces.add(iface);
1203 }
1204 }
1205 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001206 };
1207
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001208 /**
1209 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1210 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001211 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001212 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001213 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001214
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001215 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001216 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001217 }
1218
1219 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001220 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1221 if (DBG) {
1222 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001223 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001224 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001225 }
1226 }
1227
The Android Open Source Project28527d22009-03-03 19:31:44 -08001228 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001229 mContext.enforceCallingOrSelfPermission(
1230 android.Manifest.permission.ACCESS_NETWORK_STATE,
1231 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001232 }
1233
1234 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001235 mContext.enforceCallingOrSelfPermission(
1236 android.Manifest.permission.CHANGE_NETWORK_STATE,
1237 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001238 }
1239
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001240 // TODO Make this a special check when it goes public
1241 private void enforceTetherChangePermission() {
1242 mContext.enforceCallingOrSelfPermission(
1243 android.Manifest.permission.CHANGE_NETWORK_STATE,
1244 "ConnectivityService");
1245 }
1246
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001247 private void enforceTetherAccessPermission() {
1248 mContext.enforceCallingOrSelfPermission(
1249 android.Manifest.permission.ACCESS_NETWORK_STATE,
1250 "ConnectivityService");
1251 }
1252
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001253 private void enforceConnectivityInternalPermission() {
1254 mContext.enforceCallingOrSelfPermission(
1255 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1256 "ConnectivityService");
1257 }
1258
The Android Open Source Project28527d22009-03-03 19:31:44 -08001259 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001260 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1261 * network, we ignore it. If it is for the active network, we send out a
1262 * broadcast. But first, we check whether it might be possible to connect
1263 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001264 * @param info the {@code NetworkInfo} for the network
1265 */
1266 private void handleDisconnect(NetworkInfo info) {
1267
Robert Greenwalt2034b912009-08-12 16:08:25 -07001268 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001269
Robert Greenwalt2034b912009-08-12 16:08:25 -07001270 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001271 /*
1272 * If the disconnected network is not the active one, then don't report
1273 * this as a loss of connectivity. What probably happened is that we're
1274 * getting the disconnect for a network that we explicitly disabled
1275 * in accordance with network preference policies.
1276 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001277 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001278 List pids = mNetRequestersPids[prevNetType];
1279 for (int i = 0; i<pids.size(); i++) {
1280 Integer pid = (Integer)pids.get(i);
1281 // will remove them because the net's no longer connected
1282 // need to do this now as only now do we know the pids and
1283 // can properly null things that are no longer referenced.
1284 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001285 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001286 }
1287
The Android Open Source Project28527d22009-03-03 19:31:44 -08001288 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1289 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1290 if (info.isFailover()) {
1291 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1292 info.setFailover(false);
1293 }
1294 if (info.getReason() != null) {
1295 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1296 }
1297 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001298 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1299 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001300 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001301
Robert Greenwalt34848c02011-03-25 13:09:25 -07001302 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001303 tryFailover(prevNetType);
1304 if (mActiveDefaultNetwork != -1) {
1305 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001306 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1307 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001308 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001309 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1310 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001311 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001312 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001313
1314 // Reset interface if no other connections are using the same interface
1315 boolean doReset = true;
1316 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1317 if (linkProperties != null) {
1318 String oldIface = linkProperties.getInterfaceName();
1319 if (TextUtils.isEmpty(oldIface) == false) {
1320 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1321 if (networkStateTracker == null) continue;
1322 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1323 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1324 LinkProperties l = networkStateTracker.getLinkProperties();
1325 if (l == null) continue;
1326 if (oldIface.equals(l.getInterfaceName())) {
1327 doReset = false;
1328 break;
1329 }
1330 }
1331 }
1332 }
1333 }
1334
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001335 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001336 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001337
1338 sendStickyBroadcast(intent);
1339 /*
1340 * If the failover network is already connected, then immediately send
1341 * out a followup broadcast indicating successful failover
1342 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001343 if (mActiveDefaultNetwork != -1) {
1344 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001345 }
1346 }
1347
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001348 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001349 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001350 * If this is a default network, check if other defaults are available.
1351 * Try to reconnect on all available and let them hash it out when
1352 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001353 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001354 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001355 if (mActiveDefaultNetwork == prevNetType) {
1356 mActiveDefaultNetwork = -1;
1357 }
1358
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001359 // don't signal a reconnect for anything lower or equal priority than our
1360 // current connected default
1361 // TODO - don't filter by priority now - nice optimization but risky
1362// int currentPriority = -1;
1363// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001364// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001365// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001366 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001367 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001368 if (mNetConfigs[checkType] == null) continue;
1369 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001370
1371// Enabling the isAvailable() optimization caused mobile to not get
1372// selected if it was in the middle of error handling. Specifically
1373// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1374// would not be available and we wouldn't get connected to anything.
1375// So removing the isAvailable() optimization below for now. TODO: This
1376// optimization should work and we need to investigate why it doesn't work.
1377// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1378// complete before it is really complete.
1379// if (!mNetTrackers[checkType].isAvailable()) continue;
1380
Robert Greenwalt34848c02011-03-25 13:09:25 -07001381// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001382
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001383 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1384 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1385 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1386 checkInfo.setFailover(true);
1387 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001388 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001389 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001390 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001391 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001392 }
1393
1394 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001395 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1396 }
1397
1398 private void sendInetConditionBroadcast(NetworkInfo info) {
1399 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1400 }
1401
1402 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1403 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001404 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1405 if (info.isFailover()) {
1406 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1407 info.setFailover(false);
1408 }
1409 if (info.getReason() != null) {
1410 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1411 }
1412 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001413 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1414 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001415 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001416 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001417 sendStickyBroadcast(intent);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001418 }
1419
1420 /**
1421 * Called when an attempt to fail over to another network has failed.
1422 * @param info the {@link NetworkInfo} for the failed network
1423 */
1424 private void handleConnectionFailure(NetworkInfo info) {
1425 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001426
Robert Greenwalt2034b912009-08-12 16:08:25 -07001427 String reason = info.getReason();
1428 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001429
Robert Greenwalte981bc52010-10-08 16:35:52 -07001430 String reasonText;
1431 if (reason == null) {
1432 reasonText = ".";
1433 } else {
1434 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001435 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001436 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001437
1438 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1439 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1440 if (getActiveNetworkInfo() == null) {
1441 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1442 }
1443 if (reason != null) {
1444 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1445 }
1446 if (extraInfo != null) {
1447 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1448 }
1449 if (info.isFailover()) {
1450 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1451 info.setFailover(false);
1452 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001453
Robert Greenwalt34848c02011-03-25 13:09:25 -07001454 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001455 tryFailover(info.getType());
1456 if (mActiveDefaultNetwork != -1) {
1457 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001458 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1459 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001460 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001461 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1462 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001463 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001464
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001465 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001466 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001467 /*
1468 * If the failover network is already connected, then immediately send
1469 * out a followup broadcast indicating successful failover
1470 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001471 if (mActiveDefaultNetwork != -1) {
1472 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001473 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001474 }
1475
1476 private void sendStickyBroadcast(Intent intent) {
1477 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001478 if (!mSystemReady) {
1479 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001480 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001481 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1482 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001483 }
1484 }
1485
1486 void systemReady() {
1487 synchronized(this) {
1488 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001489 if (mInitialBroadcast != null) {
1490 mContext.sendStickyBroadcast(mInitialBroadcast);
1491 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001492 }
1493 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001494 // load the global proxy at startup
1495 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001496 }
1497
1498 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001499 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001500
1501 // snapshot isFailover, because sendConnectedBroadcast() resets it
1502 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001503 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001504
Robert Greenwalt2034b912009-08-12 16:08:25 -07001505 // if this is a default net and other default is running
1506 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001507 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001508 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1509 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001510 mNetConfigs[mActiveDefaultNetwork].priority >
1511 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001512 mNetworkPreference == mActiveDefaultNetwork) {
1513 // don't accept this one
Wink Savillee70c6f52010-12-03 12:01:38 -08001514 if (DBG) {
1515 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001516 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001517 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001518 teardown(thisNet);
1519 return;
1520 } else {
1521 // tear down the other
1522 NetworkStateTracker otherNet =
1523 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001524 if (DBG) {
1525 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001526 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001527 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001528 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001529 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001530 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001531 return;
1532 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001533 }
1534 }
1535 synchronized (ConnectivityService.this) {
1536 // have a new default network, release the transition wakelock in a second
1537 // if it's held. The second pause is to allow apps to reconnect over the
1538 // new network
1539 if (mNetTransitionWakeLock.isHeld()) {
1540 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001541 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001542 mNetTransitionWakeLockSerialNumber, 0),
1543 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001544 }
1545 }
1546 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001547 // this will cause us to come up initially as unconnected and switching
1548 // to connected after our normal pause unless somebody reports us as reall
1549 // disconnected
1550 mDefaultInetConditionPublished = 0;
1551 mDefaultConnectionSequence++;
1552 mInetConditionChangeInFlight = false;
1553 // Don't do this - if we never sign in stay, grey
1554 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001555 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001556 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001557 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001558 handleConnectivityChange(type, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001559 sendConnectedBroadcast(info);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001560 }
1561
The Android Open Source Project28527d22009-03-03 19:31:44 -08001562 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001563 * After a change in the connectivity state of a network. We're mainly
1564 * concerned with making sure that the list of DNS servers is set up
1565 * according to which networks are connected, and ensuring that the
1566 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001567 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001568 private void handleConnectivityChange(int netType, boolean doReset) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001569 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001570 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001571 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001572 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001573 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001574
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001575 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001576 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001577 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001578 addDefaultRoute(mNetTrackers[netType]);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001579 } else {
Robert Greenwalt1e2f2862011-04-01 10:51:22 -07001580 // many radios add a default route even when we don't want one.
1581 // remove the default route unless we need it for our active network
1582 if (mActiveDefaultNetwork != -1) {
1583 LinkProperties defaultLinkProperties =
1584 mNetTrackers[mActiveDefaultNetwork].getLinkProperties();
1585 LinkProperties newLinkProperties =
1586 mNetTrackers[netType].getLinkProperties();
1587 String defaultIface = defaultLinkProperties.getInterfaceName();
1588 if (defaultIface != null &&
1589 !defaultIface.equals(newLinkProperties.getInterfaceName())) {
1590 removeDefaultRoute(mNetTrackers[netType]);
1591 }
1592 }
Michael Jurka837e3642011-03-30 19:54:08 -07001593 addPrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001594 }
1595 } else {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001596 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001597 removeDefaultRoute(mNetTrackers[netType]);
1598 } else {
1599 removePrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001600 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001601 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001602
1603 if (doReset) {
1604 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1605 if (linkProperties != null) {
1606 String iface = linkProperties.getInterfaceName();
1607 if (TextUtils.isEmpty(iface) == false) {
1608 if (DBG) log("resetConnections(" + iface + ")");
1609 NetworkUtils.resetConnections(iface);
1610 }
1611 }
1612 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001613 }
1614
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001615 private void addPrivateDnsRoutes(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001616 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001617 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001618 if (p == null) return;
1619 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001620
1621 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001622 log("addPrivateDnsRoutes for " + nt +
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001623 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1624 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001625 if (interfaceName != null && !privateDnsRouteSet) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001626 Collection<InetAddress> dnsList = p.getDnses();
1627 for (InetAddress dns : dnsList) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001628 addHostRoute(nt, dns, 0);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001629 }
1630 nt.privateDnsRouteSet(true);
1631 }
1632 }
1633
1634 private void removePrivateDnsRoutes(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001635 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001636 if (p == null) return;
1637 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001638 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1639 if (interfaceName != null && privateDnsRouteSet) {
1640 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001641 log("removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001642 " (" + interfaceName + ")");
1643 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001644
1645 Collection<InetAddress> dnsList = p.getDnses();
1646 for (InetAddress dns : dnsList) {
1647 if (DBG) log(" removing " + dns);
1648 RouteInfo route = RouteInfo.makeHostRoute(dns);
1649 try {
1650 mNetd.removeRoute(interfaceName, route);
1651 } catch (Exception ex) {
1652 loge("error (" + ex + ") removing dns route " + route);
1653 }
1654 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001655 nt.privateDnsRouteSet(false);
1656 }
1657 }
1658
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001659
1660 private void addDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001661 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001662 if (p == null) return;
1663 String interfaceName = p.getInterfaceName();
Robert Greenwalt5c733972011-02-09 13:56:06 -08001664 if (TextUtils.isEmpty(interfaceName)) return;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001665
Robert Greenwalt355205c2011-05-10 15:05:02 -07001666 for (RouteInfo route : p.getRoutes()) {
Robert Greenwalt5a901292011-04-28 14:28:50 -07001667 //TODO - handle non-default routes
1668 if (route.isDefaultRoute()) {
Robert Greenwalt355205c2011-05-10 15:05:02 -07001669 if (DBG) log("adding default route " + route);
Robert Greenwalt5a901292011-04-28 14:28:50 -07001670 InetAddress gateway = route.getGateway();
Robert Greenwalt355205c2011-05-10 15:05:02 -07001671 if (addHostRoute(nt, gateway, 0)) {
1672 try {
1673 mNetd.addRoute(interfaceName, route);
1674 } catch (Exception e) {
1675 loge("error adding default route " + route);
1676 continue;
1677 }
Robert Greenwalt5a901292011-04-28 14:28:50 -07001678 if (DBG) {
1679 NetworkInfo networkInfo = nt.getNetworkInfo();
1680 log("addDefaultRoute for " + networkInfo.getTypeName() +
1681 " (" + interfaceName + "), GatewayAddr=" +
1682 gateway.getHostAddress());
1683 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001684 } else {
1685 loge("error adding host route for default route " + route);
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001686 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001687 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001688 }
1689 }
1690
1691
1692 public void removeDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001693 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001694 if (p == null) return;
1695 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001696
Robert Greenwalt355205c2011-05-10 15:05:02 -07001697 if (interfaceName == null) return;
1698
1699 for (RouteInfo route : p.getRoutes()) {
1700 //TODO - handle non-default routes
1701 if (route.isDefaultRoute()) {
1702 try {
1703 mNetd.removeRoute(interfaceName, route);
1704 } catch (Exception ex) {
1705 loge("error (" + ex + ") removing default route " + route);
1706 continue;
1707 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001708 if (DBG) {
1709 NetworkInfo networkInfo = nt.getNetworkInfo();
1710 log("removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1711 interfaceName + ")");
1712 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001713 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001714 }
1715 }
1716
1717 /**
1718 * Reads the network specific TCP buffer sizes from SystemProperties
1719 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1720 * wide use
1721 */
1722 public void updateNetworkSettings(NetworkStateTracker nt) {
1723 String key = nt.getTcpBufferSizesPropName();
1724 String bufferSizes = SystemProperties.get(key);
1725
1726 if (bufferSizes.length() == 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001727 loge(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001728
1729 // Setting to default values so we won't be stuck to previous values
1730 key = "net.tcp.buffersize.default";
1731 bufferSizes = SystemProperties.get(key);
1732 }
1733
1734 // Set values in kernel
1735 if (bufferSizes.length() != 0) {
1736 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001737 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001738 + "] which comes from [" + key + "]");
1739 }
1740 setBufferSize(bufferSizes);
1741 }
1742 }
1743
1744 /**
1745 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1746 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1747 *
1748 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1749 * writeMin, writeInitial, writeMax"
1750 */
1751 private void setBufferSize(String bufferSizes) {
1752 try {
1753 String[] values = bufferSizes.split(",");
1754
1755 if (values.length == 6) {
1756 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001757 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1758 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1759 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1760 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1761 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1762 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001763 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001764 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001765 }
1766 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001767 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001768 }
1769 }
1770
Robert Greenwalt2034b912009-08-12 16:08:25 -07001771 /**
1772 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1773 * on the highest priority active net which this process requested.
1774 * If there aren't any, clear it out
1775 */
1776 private void reassessPidDns(int myPid, boolean doBump)
1777 {
Wink Savillee70c6f52010-12-03 12:01:38 -08001778 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001779 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001780 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001781 continue;
1782 }
1783 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001784 if (nt.getNetworkInfo().isConnected() &&
1785 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001786 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001787 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001788 List pids = mNetRequestersPids[i];
1789 for (int j=0; j<pids.size(); j++) {
1790 Integer pid = (Integer)pids.get(j);
1791 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001792 Collection<InetAddress> dnses = p.getDnses();
1793 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001794 if (doBump) {
1795 bumpDns();
1796 }
1797 return;
1798 }
1799 }
1800 }
1801 }
1802 // nothing found - delete
1803 for (int i = 1; ; i++) {
1804 String prop = "net.dns" + i + "." + myPid;
1805 if (SystemProperties.get(prop).length() == 0) {
1806 if (doBump) {
1807 bumpDns();
1808 }
1809 return;
1810 }
1811 SystemProperties.set(prop, "");
1812 }
1813 }
1814
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001815 // return true if results in a change
1816 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001817 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001818 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001819 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001820 String dnsString = dns.getHostAddress();
1821 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1822 changed = true;
1823 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1824 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001825 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001826 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001827 }
1828
1829 private void bumpDns() {
1830 /*
1831 * Bump the property that tells the name resolver library to reread
1832 * the DNS server list from the properties.
1833 */
1834 String propVal = SystemProperties.get("net.dnschange");
1835 int n = 0;
1836 if (propVal.length() != 0) {
1837 try {
1838 n = Integer.parseInt(propVal);
1839 } catch (NumberFormatException e) {}
1840 }
1841 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001842 /*
1843 * Tell the VMs to toss their DNS caches
1844 */
1845 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1846 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08001847 /*
1848 * Connectivity events can happen before boot has completed ...
1849 */
1850 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07001851 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001852 }
1853
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001854 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001855 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001856 NetworkStateTracker nt = mNetTrackers[netType];
1857 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001858 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001859 if (p == null) return;
1860 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001861 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001862 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001863 int j = 1;
Robert Greenwalt94daa182010-09-01 11:34:05 -07001864 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001865 String dnsString = mDefaultDns.getHostAddress();
1866 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1867 if (DBG) {
1868 log("no dns provided - using " + dnsString);
1869 }
1870 changed = true;
1871 SystemProperties.set("net.dns1", dnsString);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001872 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001873 j++;
1874 } else {
1875 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001876 String dnsString = dns.getHostAddress();
1877 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1878 j++;
1879 continue;
1880 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001881 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001882 log("adding dns " + dns + " for " +
Robert Greenwalt94daa182010-09-01 11:34:05 -07001883 nt.getNetworkInfo().getTypeName());
1884 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001885 changed = true;
1886 SystemProperties.set("net.dns" + j++, dnsString);
Robert Greenwalt94daa182010-09-01 11:34:05 -07001887 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001888 }
1889 for (int k=j ; k<mNumDnsEntries; k++) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001890 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1891 if (DBG) log("erasing net.dns" + k);
1892 changed = true;
1893 SystemProperties.set("net.dns" + k, "");
1894 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001895 }
1896 mNumDnsEntries = j;
1897 } else {
1898 // set per-pid dns for attached secondary nets
1899 List pids = mNetRequestersPids[netType];
1900 for (int y=0; y< pids.size(); y++) {
1901 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001902 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001903 }
1904 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001905 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001906 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001907 }
1908
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001909 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001910 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1911 NETWORK_RESTORE_DELAY_PROP_NAME);
1912 if(restoreDefaultNetworkDelayStr != null &&
1913 restoreDefaultNetworkDelayStr.length() != 0) {
1914 try {
1915 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1916 } catch (NumberFormatException e) {
1917 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001918 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001919 // if the system property isn't set, use the value for the apn type
1920 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1921
1922 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1923 (mNetConfigs[networkType] != null)) {
1924 ret = mNetConfigs[networkType].restoreTime;
1925 }
1926 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001927 }
1928
1929 @Override
1930 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001931 if (mContext.checkCallingOrSelfPermission(
1932 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001933 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001934 pw.println("Permission Denial: can't dump ConnectivityService " +
1935 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1936 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001937 return;
1938 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001939 pw.println();
1940 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001941 if (nst != null) {
1942 if (nst.getNetworkInfo().isConnected()) {
1943 pw.println("Active network: " + nst.getNetworkInfo().
1944 getTypeName());
1945 }
1946 pw.println(nst.getNetworkInfo());
1947 pw.println(nst);
1948 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001949 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001950 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001951
1952 pw.println("Network Requester Pids:");
1953 for (int net : mPriorityList) {
1954 String pidString = net + ": ";
1955 for (Object pid : mNetRequestersPids[net]) {
1956 pidString = pidString + pid.toString() + ", ";
1957 }
1958 pw.println(pidString);
1959 }
1960 pw.println();
1961
1962 pw.println("FeatureUsers:");
1963 for (Object requester : mFeatureUsers) {
1964 pw.println(requester.toString());
1965 }
1966 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001967
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001968 synchronized (this) {
1969 pw.println("NetworkTranstionWakeLock is currently " +
1970 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1971 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1972 }
1973 pw.println();
1974
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001975 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07001976
1977 if (mInetLog != null) {
1978 pw.println();
1979 pw.println("Inet condition reports:");
1980 for(int i = 0; i < mInetLog.size(); i++) {
1981 pw.println(mInetLog.get(i));
1982 }
1983 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001984 }
1985
Robert Greenwalt2034b912009-08-12 16:08:25 -07001986 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001987 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07001988 public MyHandler(Looper looper) {
1989 super(looper);
1990 }
1991
The Android Open Source Project28527d22009-03-03 19:31:44 -08001992 @Override
1993 public void handleMessage(Message msg) {
1994 NetworkInfo info;
1995 switch (msg.what) {
1996 case NetworkStateTracker.EVENT_STATE_CHANGED:
1997 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08001998 int type = info.getType();
1999 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002000
Wink Savillee70c6f52010-12-03 12:01:38 -08002001 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002002 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002003 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002004
2005 // Connectivity state changed:
2006 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07002007 // [12-9] Network subtype (for mobile network, as defined
2008 // by TelephonyManager)
2009 // [8-3] Detailed state ordinal (as defined by
2010 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002011 // [2-0] Network type (as defined by ConnectivityManager)
2012 int eventLogParam = (info.getType() & 0x7) |
2013 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2014 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08002015 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07002016 eventLogParam);
2017
2018 if (info.getDetailedState() ==
2019 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002020 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002021 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002022 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002023 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002024 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002025 // the logic here is, handle SUSPENDED the same as
2026 // DISCONNECTED. The only difference being we are
2027 // broadcasting an intent with NetworkInfo that's
2028 // suspended. This allows the applications an
2029 // opportunity to handle DISCONNECTED and SUSPENDED
2030 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002031 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002032 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002033 handleConnect(info);
2034 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002035 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002036 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002037 info = (NetworkInfo) msg.obj;
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002038 handleConnectivityChange(info.getType(), true);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002039 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002040 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002041 String causedBy = null;
2042 synchronized (ConnectivityService.this) {
2043 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2044 mNetTransitionWakeLock.isHeld()) {
2045 mNetTransitionWakeLock.release();
2046 causedBy = mNetTransitionWakeLockCausedBy;
2047 }
2048 }
2049 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002050 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002051 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002052 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002053 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002054 FeatureUser u = (FeatureUser)msg.obj;
2055 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002056 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002057 case EVENT_INET_CONDITION_CHANGE:
2058 {
2059 int netType = msg.arg1;
2060 int condition = msg.arg2;
2061 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002062 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002063 }
2064 case EVENT_INET_CONDITION_HOLD_END:
2065 {
2066 int netType = msg.arg1;
2067 int sequence = msg.arg2;
2068 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002069 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002070 }
2071 case EVENT_SET_NETWORK_PREFERENCE:
2072 {
2073 int preference = msg.arg1;
2074 handleSetNetworkPreference(preference);
2075 break;
2076 }
2077 case EVENT_SET_BACKGROUND_DATA:
2078 {
2079 boolean enabled = (msg.arg1 == ENABLED);
2080 handleSetBackgroundData(enabled);
2081 break;
2082 }
2083 case EVENT_SET_MOBILE_DATA:
2084 {
2085 boolean enabled = (msg.arg1 == ENABLED);
2086 handleSetMobileData(enabled);
2087 break;
2088 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002089 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2090 {
2091 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002092 break;
2093 }
2094 case EVENT_SET_DEPENDENCY_MET:
2095 {
2096 boolean met = (msg.arg1 == ENABLED);
2097 handleSetDependencyMet(msg.arg2, met);
2098 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002099 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002100 }
2101 }
2102 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002103
2104 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002105 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002106 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002107
2108 if (isTetheringSupported()) {
2109 return mTethering.tether(iface);
2110 } else {
2111 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2112 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002113 }
2114
2115 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002116 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002117 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002118
2119 if (isTetheringSupported()) {
2120 return mTethering.untether(iface);
2121 } else {
2122 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2123 }
2124 }
2125
2126 // javadoc from interface
2127 public int getLastTetherError(String iface) {
2128 enforceTetherAccessPermission();
2129
2130 if (isTetheringSupported()) {
2131 return mTethering.getLastTetherError(iface);
2132 } else {
2133 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2134 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002135 }
2136
2137 // TODO - proper iface API for selection by property, inspection, etc
2138 public String[] getTetherableUsbRegexs() {
2139 enforceTetherAccessPermission();
2140 if (isTetheringSupported()) {
2141 return mTethering.getTetherableUsbRegexs();
2142 } else {
2143 return new String[0];
2144 }
2145 }
2146
2147 public String[] getTetherableWifiRegexs() {
2148 enforceTetherAccessPermission();
2149 if (isTetheringSupported()) {
2150 return mTethering.getTetherableWifiRegexs();
2151 } else {
2152 return new String[0];
2153 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002154 }
2155
Danica Chang96567052010-08-11 14:54:43 -07002156 public String[] getTetherableBluetoothRegexs() {
2157 enforceTetherAccessPermission();
2158 if (isTetheringSupported()) {
2159 return mTethering.getTetherableBluetoothRegexs();
2160 } else {
2161 return new String[0];
2162 }
2163 }
2164
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002165 // TODO - move iface listing, queries, etc to new module
2166 // javadoc from interface
2167 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002168 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002169 return mTethering.getTetherableIfaces();
2170 }
2171
2172 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002173 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002174 return mTethering.getTetheredIfaces();
2175 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002176
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002177 public String[] getTetheringErroredIfaces() {
2178 enforceTetherAccessPermission();
2179 return mTethering.getErroredIfaces();
2180 }
2181
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002182 // if ro.tether.denied = true we default to no tethering
2183 // gservices could set the secure setting to 1 though to enable it on a build where it
2184 // had previously been turned off.
2185 public boolean isTetheringSupported() {
2186 enforceTetherAccessPermission();
2187 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002188 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2189 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2190 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002191 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002192
2193 // An API NetworkStateTrackers can call when they lose their network.
2194 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2195 // whichever happens first. The timer is started by the first caller and not
2196 // restarted by subsequent callers.
2197 public void requestNetworkTransitionWakelock(String forWhom) {
2198 enforceConnectivityInternalPermission();
2199 synchronized (this) {
2200 if (mNetTransitionWakeLock.isHeld()) return;
2201 mNetTransitionWakeLockSerialNumber++;
2202 mNetTransitionWakeLock.acquire();
2203 mNetTransitionWakeLockCausedBy = forWhom;
2204 }
2205 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002206 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002207 mNetTransitionWakeLockSerialNumber, 0),
2208 mNetTransitionWakeLockTimeout);
2209 return;
2210 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002211
Robert Greenwalt986c7412010-09-08 15:24:47 -07002212 // 100 percent is full good, 0 is full bad.
2213 public void reportInetCondition(int networkType, int percentage) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002214 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002215 mContext.enforceCallingOrSelfPermission(
2216 android.Manifest.permission.STATUS_BAR,
2217 "ConnectivityService");
2218
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002219 if (DBG) {
2220 int pid = getCallingPid();
2221 int uid = getCallingUid();
2222 String s = pid + "(" + uid + ") reports inet is " +
2223 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2224 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2225 mInetLog.add(s);
2226 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2227 mInetLog.remove(0);
2228 }
2229 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002230 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002231 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2232 }
2233
2234 private void handleInetConditionChange(int netType, int condition) {
2235 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002236 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002237 netType + ", condition=" + condition +
2238 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2239 }
2240 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002241 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002242 return;
2243 }
2244 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002245 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002246 return;
2247 }
2248 mDefaultInetCondition = condition;
2249 int delay;
2250 if (mInetConditionChangeInFlight == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002251 if (DBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002252 // setup a new hold to debounce this
2253 if (mDefaultInetCondition > 50) {
2254 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2255 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2256 } else {
2257 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2258 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2259 }
2260 mInetConditionChangeInFlight = true;
2261 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2262 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2263 } else {
2264 // we've set the new condition, when this hold ends that will get
2265 // picked up
Wink Savillee70c6f52010-12-03 12:01:38 -08002266 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002267 }
2268 }
2269
2270 private void handleInetConditionHoldEnd(int netType, int sequence) {
2271 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002272 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002273 ", condition =" + mDefaultInetCondition +
2274 ", published condition =" + mDefaultInetConditionPublished);
2275 }
2276 mInetConditionChangeInFlight = false;
2277
2278 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002279 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002280 return;
2281 }
2282 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002283 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002284 return;
2285 }
2286 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002287 if (DBG) log("no change in condition - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002288 return;
2289 }
2290 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2291 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002292 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002293 return;
2294 }
2295 mDefaultInetConditionPublished = mDefaultInetCondition;
2296 sendInetConditionBroadcast(networkInfo);
2297 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002298 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002299
2300 public synchronized ProxyProperties getProxy() {
2301 if (mGlobalProxy != null) return mGlobalProxy;
2302 if (mDefaultProxy != null) return mDefaultProxy;
2303 return null;
2304 }
2305
2306 public void setGlobalProxy(ProxyProperties proxyProperties) {
2307 enforceChangePermission();
2308 synchronized (mGlobalProxyLock) {
2309 if (proxyProperties == mGlobalProxy) return;
2310 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2311 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2312
2313 String host = "";
2314 int port = 0;
2315 String exclList = "";
2316 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2317 mGlobalProxy = new ProxyProperties(proxyProperties);
2318 host = mGlobalProxy.getHost();
2319 port = mGlobalProxy.getPort();
2320 exclList = mGlobalProxy.getExclusionList();
2321 } else {
2322 mGlobalProxy = null;
2323 }
2324 ContentResolver res = mContext.getContentResolver();
2325 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2326 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002327 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002328 exclList);
2329 }
2330
2331 if (mGlobalProxy == null) {
2332 proxyProperties = mDefaultProxy;
2333 }
2334 sendProxyBroadcast(proxyProperties);
2335 }
2336
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002337 private void loadGlobalProxy() {
2338 ContentResolver res = mContext.getContentResolver();
2339 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2340 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2341 String exclList = Settings.Secure.getString(res,
2342 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2343 if (!TextUtils.isEmpty(host)) {
2344 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2345 synchronized (mGlobalProxyLock) {
2346 mGlobalProxy = proxyProperties;
2347 }
2348 }
2349 }
2350
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002351 public ProxyProperties getGlobalProxy() {
2352 synchronized (mGlobalProxyLock) {
2353 return mGlobalProxy;
2354 }
2355 }
2356
2357 private void handleApplyDefaultProxy(int type) {
2358 // check if new default - push it out to all VM if so
2359 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2360 synchronized (this) {
2361 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2362 if (mDefaultProxy == proxy) return;
2363 if (!TextUtils.isEmpty(proxy.getHost())) {
2364 mDefaultProxy = proxy;
2365 } else {
2366 mDefaultProxy = null;
2367 }
2368 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002369 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002370 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2371 if (mGlobalProxy != null) return;
2372 sendProxyBroadcast(proxy);
2373 }
2374
2375 private void handleDeprecatedGlobalHttpProxy() {
2376 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2377 Settings.Secure.HTTP_PROXY);
2378 if (!TextUtils.isEmpty(proxy)) {
2379 String data[] = proxy.split(":");
2380 String proxyHost = data[0];
2381 int proxyPort = 8080;
2382 if (data.length > 1) {
2383 try {
2384 proxyPort = Integer.parseInt(data[1]);
2385 } catch (NumberFormatException e) {
2386 return;
2387 }
2388 }
2389 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2390 setGlobalProxy(p);
2391 }
2392 }
2393
2394 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002395 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savillee70c6f52010-12-03 12:01:38 -08002396 log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002397 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002398 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2399 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002400 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002401 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002402 }
2403
2404 private static class SettingsObserver extends ContentObserver {
2405 private int mWhat;
2406 private Handler mHandler;
2407 SettingsObserver(Handler handler, int what) {
2408 super(handler);
2409 mHandler = handler;
2410 mWhat = what;
2411 }
2412
2413 void observe(Context context) {
2414 ContentResolver resolver = context.getContentResolver();
2415 resolver.registerContentObserver(Settings.Secure.getUriFor(
2416 Settings.Secure.HTTP_PROXY), false, this);
2417 }
2418
2419 @Override
2420 public void onChange(boolean selfChange) {
2421 mHandler.obtainMessage(mWhat).sendToTarget();
2422 }
2423 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002424
2425 private void log(String s) {
2426 Slog.d(TAG, s);
2427 }
2428
2429 private void loge(String s) {
2430 Slog.e(TAG, s);
2431 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002432
Wink Savillef6b76692011-02-24 17:58:51 -08002433 int convertFeatureToNetworkType(String feature){
2434 int networkType = -1;
2435 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2436 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2437 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2438 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2439 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2440 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2441 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2442 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2443 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2444 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2445 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2446 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2447 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2448 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2449 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2450 }
2451 return networkType;
2452 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002453
2454 private static <T> T checkNotNull(T value, String message) {
2455 if (value == null) {
2456 throw new NullPointerException(message);
2457 }
2458 return value;
2459 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002460
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002461 /**
2462 * Protect a socket from VPN routing rules. This method is used by
2463 * VpnBuilder and not available in ConnectivityManager. Permission
2464 * checks are done in Vpn class.
2465 * @hide
2466 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002467 @Override
2468 public void protectVpn(ParcelFileDescriptor socket) {
2469 mVpn.protect(socket, getDefaultInterface());
2470 }
2471
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002472 /**
2473 * Prepare for a VPN application. This method is used by VpnDialogs
2474 * and not available in ConnectivityManager. Permission checks are
2475 * done in Vpn class.
2476 * @hide
2477 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002478 @Override
2479 public String prepareVpn(String packageName) {
2480 return mVpn.prepare(packageName);
2481 }
2482
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002483 /**
2484 * Configure a TUN interface and return its file descriptor. Parameters
2485 * are encoded and opaque to this class. This method is used by VpnBuilder
2486 * and not available in ConnectivityManager. Permission checks are done
2487 * in Vpn class.
2488 * @hide
2489 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002490 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002491 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002492 return mVpn.establish(config);
2493 }
2494
2495 private String getDefaultInterface() {
2496 if (ConnectivityManager.isNetworkTypeValid(mActiveDefaultNetwork)) {
2497 NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
2498 if (tracker != null) {
2499 LinkProperties properties = tracker.getLinkProperties();
2500 if (properties != null) {
2501 return properties.getInterfaceName();
2502 }
2503 }
2504 }
2505 throw new IllegalStateException("No default interface");
2506 }
2507
2508 /**
2509 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2510 * through NetworkStateTracker since it works differently. For example, it
2511 * needs to override DNS servers but never takes the default routes. It
2512 * relies on another data network, and it could keep existing connections
2513 * alive after reconnecting, switching between networks, or even resuming
2514 * from deep sleep. Calls from applications should be done synchronously
2515 * to avoid race conditions. As these are all hidden APIs, refactoring can
2516 * be done whenever a better abstraction is developed.
2517 */
2518 public class VpnCallback {
2519
2520 private VpnCallback() {
2521 }
2522
2523 public synchronized void override(String[] dnsServers) {
2524 // TODO: override DNS servers and http proxy.
2525 }
2526
2527 public synchronized void restore() {
2528 // TODO: restore VPN changes.
2529 }
2530 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002531}