blob: afc04bb841b3d819e3b25f20854b4886e7118855 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey1a303952011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070020import static android.net.ConnectivityManager.isNetworkTypeValid;
21import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070022import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070023
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080024import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.PackageManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070029import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080031import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080032import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.net.IConnectivityManager;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034import android.net.INetworkPolicyListener;
35import android.net.INetworkPolicyManager;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080036import android.net.LinkProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070038import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070040import android.net.NetworkInfo.DetailedState;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070041import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070043import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070044import android.net.Proxy;
45import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070046import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.net.wifi.WifiStateTracker;
48import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040049import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070051import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070052import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070053import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.Looper;
55import android.os.Message;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070056import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070057import android.os.PowerManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070058import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.ServiceManager;
60import android.os.SystemProperties;
61import android.provider.Settings;
Robert Greenwalt42acef32009-08-12 16:08:25 -070062import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080064import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070065import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070067import com.android.internal.net.VpnConfig;
Robert Greenwalt42acef32009-08-12 16:08:25 -070068import com.android.internal.telephony.Phone;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080069import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070070import com.android.server.connectivity.Vpn;
71
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070072import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070073import com.google.android.collect.Sets;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -070076import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import java.io.PrintWriter;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070078import java.net.InetAddress;
79import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -070080import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070081import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070082import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -070083import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070084import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -070085import java.util.List;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070086import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087
88/**
89 * @hide
90 */
91public class ConnectivityService extends IConnectivityManager.Stub {
92
Robert Greenwaltba175a52010-10-05 19:12:26 -070093 private static final boolean DBG = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 private static final String TAG = "ConnectivityService";
95
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070096 private static final boolean LOGD_RULES = false;
97
Robert Greenwalt42acef32009-08-12 16:08:25 -070098 // how long to wait before switching back to a radio's default network
99 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
100 // system property that can override the above value
101 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
102 "android.telephony.apn-restore";
103
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700104 // used in recursive route setting to add gateways for the host for which
105 // a host route was requested.
106 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
107
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800108 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800109 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800110
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700111 private Vpn mVpn;
112
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700113 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
114 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700115 /** Currently active network rules by UID. */
116 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700117 /** Set of ifaces that are costly. */
118 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 /**
121 * Sometimes we want to refer to the individual network state
122 * trackers separately, and sometimes we just want to treat them
123 * abstractly.
124 */
125 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700126
127 /**
128 * A per Net list of the PID's that requested access to the net
129 * used both as a refcount and for per-PID DNS selection
130 */
131 private List mNetRequestersPids[];
132
Robert Greenwalt42acef32009-08-12 16:08:25 -0700133 // priority order of the nettrackers
134 // (excluding dynamically set mNetworkPreference)
135 // TODO - move mNetworkTypePreference into this
136 private int[] mPriorityList;
137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 private Context mContext;
139 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700140 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700141 // 0 is full bad, 100 is full good
142 private int mDefaultInetCondition = 0;
143 private int mDefaultInetConditionPublished = 0;
144 private boolean mInetConditionChangeInFlight = false;
145 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146
147 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148
149 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700150 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
Robert Greenwaltd825ea42010-12-29 16:15:02 -0800152 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
153
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700154 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700155 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700156
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700157 private static final int ENABLED = 1;
158 private static final int DISABLED = 0;
159
160 // Share the event space with NetworkStateTracker (which can't see this
161 // internal class but sends us events). If you change these, change
162 // NetworkStateTracker.java too.
163 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
164 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
165
166 /**
167 * used internally as a delayed event to make us switch back to the
168 * default network
169 */
170 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
171 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
172
173 /**
174 * used internally to change our mobile data enabled flag
175 */
176 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
177 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
178
179 /**
180 * used internally to change our network preference setting
181 * arg1 = networkType to prefer
182 */
183 private static final int EVENT_SET_NETWORK_PREFERENCE =
184 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
185
186 /**
187 * used internally to synchronize inet condition reports
188 * arg1 = networkType
189 * arg2 = condition (0 bad, 100 good)
190 */
191 private static final int EVENT_INET_CONDITION_CHANGE =
192 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
193
194 /**
195 * used internally to mark the end of inet condition hold periods
196 * arg1 = networkType
197 */
198 private static final int EVENT_INET_CONDITION_HOLD_END =
199 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
200
201 /**
202 * used internally to set the background data preference
203 * arg1 = TRUE for enabled, FALSE for disabled
204 */
205 private static final int EVENT_SET_BACKGROUND_DATA =
206 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
207
208 /**
209 * used internally to set enable/disable cellular data
210 * arg1 = ENBALED or DISABLED
211 */
212 private static final int EVENT_SET_MOBILE_DATA =
213 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
214
Robert Greenwaltf3331232010-09-24 14:32:21 -0700215 /**
216 * used internally to clear a wakelock when transitioning
217 * from one net to another
218 */
219 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
220 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
221
Robert Greenwalt434203a2010-10-11 16:00:27 -0700222 /**
223 * used internally to reload global proxy settings
224 */
225 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
226 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
227
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700228 /**
229 * used internally to set external dependency met/unmet
230 * arg1 = ENABLED (met) or DISABLED (unmet)
231 * arg2 = NetworkType
232 */
233 private static final int EVENT_SET_DEPENDENCY_MET =
234 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
235
Robert Greenwalt42acef32009-08-12 16:08:25 -0700236 private Handler mHandler;
237
238 // list of DeathRecipients used to make sure features are turned off when
239 // a process dies
240 private List mFeatureUsers;
241
Mike Lockwood0f79b542009-08-14 14:18:49 -0400242 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800243 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400244
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700245 private PowerManager.WakeLock mNetTransitionWakeLock;
246 private String mNetTransitionWakeLockCausedBy = "";
247 private int mNetTransitionWakeLockSerialNumber;
248 private int mNetTransitionWakeLockTimeout;
249
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700250 private InetAddress mDefaultDns;
251
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700252 // used in DBG mode to track inet condition reports
253 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
254 private ArrayList mInetLog;
255
Robert Greenwalt434203a2010-10-11 16:00:27 -0700256 // track the current default http proxy - tell the world if we get a new one (real change)
257 private ProxyProperties mDefaultProxy = null;
258 // track the global proxy.
259 private ProxyProperties mGlobalProxy = null;
260 private final Object mGlobalProxyLock = new Object();
261
262 private SettingsObserver mSettingsObserver;
263
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700264 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700265 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700266
Robert Greenwalt511288a2009-12-07 11:33:18 -0800267 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700268 public int mSimultaneity;
269 public int mType;
270 public RadioAttributes(String init) {
271 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700272 mType = Integer.parseInt(fragments[0]);
273 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700274 }
275 }
276 RadioAttributes[] mRadioAttributes;
277
Robert Greenwalt50393202011-06-21 17:26:14 -0700278 // the set of network types that can only be enabled by system/sig apps
279 List mProtectedNetworks;
280
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700281 public ConnectivityService(
282 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800283 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800284
Wink Savillebb08caf2010-09-02 19:23:52 -0700285 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
286 handlerThread.start();
287 mHandler = new MyHandler(handlerThread.getLooper());
288
Robert Greenwaltd825ea42010-12-29 16:15:02 -0800289 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
290 Settings.Secure.BACKGROUND_DATA, 1) == 1);
291
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800292 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800293 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
294 String id = Settings.Secure.getString(context.getContentResolver(),
295 Settings.Secure.ANDROID_ID);
296 if (id != null && id.length() > 0) {
297 String name = new String("android_").concat(id);
298 SystemProperties.set("net.hostname", name);
299 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800300 }
301
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700302 // read our default dns server ip
303 String dns = Settings.Secure.getString(context.getContentResolver(),
304 Settings.Secure.DEFAULT_DNS_SERVER);
305 if (dns == null || dns.length() == 0) {
306 dns = context.getResources().getString(
307 com.android.internal.R.string.config_default_dns_server);
308 }
309 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800310 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
311 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800312 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700313 }
314
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700315 mContext = checkNotNull(context, "missing Context");
316 mNetd = checkNotNull(netd, "missing INetworkManagementService");
317 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700318
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700319 try {
320 mPolicyManager.registerListener(mPolicyListener);
321 } catch (RemoteException e) {
322 // ouch, no rules updates means some processes may never get network
323 Slog.e(TAG, "unable to register INetworkPolicyListener", e);
324 }
325
326 final PowerManager powerManager = (PowerManager) context.getSystemService(
327 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700328 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
329 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
330 com.android.internal.R.integer.config_networkTransitionTimeout);
331
Robert Greenwalt42acef32009-08-12 16:08:25 -0700332 mNetTrackers = new NetworkStateTracker[
333 ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700336
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700337 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700338 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700339
Robert Greenwalt42acef32009-08-12 16:08:25 -0700340 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700341 String[] raStrings = context.getResources().getStringArray(
342 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700343 for (String raString : raStrings) {
344 RadioAttributes r = new RadioAttributes(raString);
345 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800346 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700347 continue;
348 }
349 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800350 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700351 r.mType);
352 continue;
353 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700354 mRadioAttributes[r.mType] = r;
355 }
356
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700357 String[] naStrings = context.getResources().getStringArray(
358 com.android.internal.R.array.networkAttributes);
359 for (String naString : naStrings) {
360 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700361 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700362 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800363 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700364 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700365 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700366 }
Wink Saville975c8482011-04-07 14:23:45 -0700367 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800368 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700369 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700370 continue;
371 }
Wink Saville975c8482011-04-07 14:23:45 -0700372 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800373 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700374 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700375 continue;
376 }
Wink Saville975c8482011-04-07 14:23:45 -0700377 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700378 mNetworksDefined++;
379 } catch(Exception e) {
380 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700381 }
382 }
383
Robert Greenwalt50393202011-06-21 17:26:14 -0700384 mProtectedNetworks = new ArrayList<Integer>();
385 int[] protectedNetworks = context.getResources().getIntArray(
386 com.android.internal.R.array.config_protectedNetworks);
387 for (int p : protectedNetworks) {
388 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
389 mProtectedNetworks.add(p);
390 } else {
391 if (DBG) loge("Ignoring protectedNetwork " + p);
392 }
393 }
394
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700395 // high priority first
396 mPriorityList = new int[mNetworksDefined];
397 {
398 int insertionPoint = mNetworksDefined-1;
399 int currentLowest = 0;
400 int nextLowest = 0;
401 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700402 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700403 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700404 if (na.priority < currentLowest) continue;
405 if (na.priority > currentLowest) {
406 if (na.priority < nextLowest || nextLowest == 0) {
407 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700408 }
409 continue;
410 }
Wink Saville975c8482011-04-07 14:23:45 -0700411 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700412 }
413 currentLowest = nextLowest;
414 nextLowest = 0;
415 }
416 }
417
418 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
419 for (int i : mPriorityList) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700420 mNetRequestersPids[i] = new ArrayList();
421 }
422
423 mFeatureUsers = new ArrayList();
424
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700425 mNumDnsEntries = 0;
426
427 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
428 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 /*
430 * Create the network state trackers for Wi-Fi and mobile
431 * data. Maybe this could be done with a factory class,
432 * but it's not clear that it's worth it, given that
433 * the number of different network types is not going
434 * to change very often.
435 */
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700436 for (int netType : mPriorityList) {
Wink Saville975c8482011-04-07 14:23:45 -0700437 switch (mNetConfigs[netType].radio) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700438 case ConnectivityManager.TYPE_WIFI:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800439 if (DBG) log("Starting Wifi Service.");
Wink Savillec7a98342010-08-13 16:11:42 -0700440 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700441 WifiService wifiService = new WifiService(context);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700442 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700443 wifiService.checkAndStartWifi();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700444 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Savillec7a98342010-08-13 16:11:42 -0700445 wst.startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700446 break;
447 case ConnectivityManager.TYPE_MOBILE:
Wink Savillec7a98342010-08-13 16:11:42 -0700448 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700449 mNetConfigs[netType].name);
Wink Savillec7a98342010-08-13 16:11:42 -0700450 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700451 break;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800452 case ConnectivityManager.TYPE_DUMMY:
453 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700454 mNetConfigs[netType].name);
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800455 mNetTrackers[netType].startMonitoring(context, mHandler);
456 break;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800457 case ConnectivityManager.TYPE_BLUETOOTH:
458 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
459 mNetTrackers[netType].startMonitoring(context, mHandler);
460 break;
Benoit Goby19970692010-12-22 14:29:40 -0800461 case ConnectivityManager.TYPE_ETHERNET:
462 mNetTrackers[netType] = EthernetDataTracker.getInstance();
463 mNetTrackers[netType].startMonitoring(context, mHandler);
464 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700465 default:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800466 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Saville975c8482011-04-07 14:23:45 -0700467 mNetConfigs[netType].radio);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700468 continue;
469 }
470 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800471
Chia-chi Yehc9338302011-05-11 16:35:13 -0700472 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
473 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
474
475 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700476 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700477 mTethering.getTetherableWifiRegexs().length != 0 ||
478 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700479 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800480
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700481 mVpn = new Vpn(mContext, new VpnCallback());
482
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700483 try {
484 nmService.registerObserver(mTethering);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700485 nmService.registerObserver(mVpn);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700486 } catch (RemoteException e) {
487 loge("Error registering observer :" + e);
488 }
489
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700490 if (DBG) {
491 mInetLog = new ArrayList();
492 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700493
494 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
495 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800496
497 loadGlobalProxy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 }
499
500 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700501 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 * @param preference the new preference
503 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700504 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700506
507 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 }
509
510 public int getNetworkPreference() {
511 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700512 int preference;
513 synchronized(this) {
514 preference = mNetworkPreference;
515 }
516 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 }
518
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700519 private void handleSetNetworkPreference(int preference) {
520 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700521 mNetConfigs[preference] != null &&
522 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700523 if (mNetworkPreference != preference) {
524 final ContentResolver cr = mContext.getContentResolver();
525 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
526 synchronized(this) {
527 mNetworkPreference = preference;
528 }
529 enforcePreference();
530 }
531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 private int getPersistedNetworkPreference() {
535 final ContentResolver cr = mContext.getContentResolver();
536
537 final int networkPrefSetting = Settings.Secure
538 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
539 if (networkPrefSetting != -1) {
540 return networkPrefSetting;
541 }
542
543 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
544 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700547 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548 * In this method, we only tear down a non-preferred network. Establishing
549 * a connection to the preferred network is taken care of when we handle
550 * the disconnect event from the non-preferred network
551 * (see {@link #handleDisconnect(NetworkInfo)}).
552 */
553 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700554 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555 return;
556
Robert Greenwalt42acef32009-08-12 16:08:25 -0700557 if (!mNetTrackers[mNetworkPreference].isAvailable())
558 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559
Robert Greenwalt42acef32009-08-12 16:08:25 -0700560 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700561 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700562 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700563 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800564 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700565 " in enforcePreference");
566 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700567 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 }
569 }
570 }
571
572 private boolean teardown(NetworkStateTracker netTracker) {
573 if (netTracker.teardown()) {
574 netTracker.setTeardownRequested(true);
575 return true;
576 } else {
577 return false;
578 }
579 }
580
581 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700582 * Check if UID should be blocked from using the network represented by the
583 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700584 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700585 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
586 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700587
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700588 final boolean networkCostly;
589 final int uidRules;
590 synchronized (mRulesLock) {
591 networkCostly = mMeteredIfaces.contains(iface);
592 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700593 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700594
595 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
596 return true;
597 }
598
599 // no restrictive rules; network is visible
600 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700601 }
602
603 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700604 * Return a filtered {@link NetworkInfo}, potentially marked
605 * {@link DetailedState#BLOCKED} based on
606 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700607 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700608 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
609 NetworkInfo info = tracker.getNetworkInfo();
610 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700611 // network is blocked; clone and override state
612 info = new NetworkInfo(info);
613 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700614 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700615 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700616 }
617
618 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 * Return NetworkInfo for the active (i.e., connected) network interface.
620 * It is assumed that at most one network is active at a time. If more
621 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700622 * @return the info for the active network, or {@code null} if none is
623 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700625 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700627 enforceAccessPermission();
628 final int uid = Binder.getCallingUid();
629 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 }
631
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700632 @Override
633 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
634 enforceConnectivityInternalPermission();
635 return getNetworkInfo(mActiveDefaultNetwork, uid);
636 }
637
638 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 public NetworkInfo getNetworkInfo(int networkType) {
640 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700641 final int uid = Binder.getCallingUid();
642 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 }
644
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700645 private NetworkInfo getNetworkInfo(int networkType, int uid) {
646 NetworkInfo info = null;
647 if (isNetworkTypeValid(networkType)) {
648 final NetworkStateTracker tracker = mNetTrackers[networkType];
649 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700650 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700651 }
652 }
653 return info;
654 }
655
656 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 public NetworkInfo[] getAllNetworkInfo() {
658 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700659 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700660 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700661 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700662 for (NetworkStateTracker tracker : mNetTrackers) {
663 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700664 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700665 }
666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700668 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 }
670
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700671 /**
672 * Return LinkProperties for the active (i.e., connected) default
673 * network interface. It is assumed that at most one default network
674 * is active at a time. If more than one is active, it is indeterminate
675 * which will be returned.
676 * @return the ip properties for the active network, or {@code null} if
677 * none is active
678 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700679 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700680 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700681 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700682 }
683
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700684 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700685 public LinkProperties getLinkProperties(int networkType) {
686 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700687 if (isNetworkTypeValid(networkType)) {
688 final NetworkStateTracker tracker = mNetTrackers[networkType];
689 if (tracker != null) {
690 return tracker.getLinkProperties();
691 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700692 }
693 return null;
694 }
695
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700696 @Override
697 public NetworkState[] getAllNetworkState() {
698 enforceAccessPermission();
699 final int uid = Binder.getCallingUid();
700 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700701 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700702 for (NetworkStateTracker tracker : mNetTrackers) {
703 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700704 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700705 result.add(new NetworkState(
706 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
707 }
708 }
709 }
710 return result.toArray(new NetworkState[result.size()]);
711 }
712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 public boolean setRadios(boolean turnOn) {
714 boolean result = true;
715 enforceChangePermission();
716 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700717 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 }
719 return result;
720 }
721
722 public boolean setRadio(int netType, boolean turnOn) {
723 enforceChangePermission();
724 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
725 return false;
726 }
727 NetworkStateTracker tracker = mNetTrackers[netType];
728 return tracker != null && tracker.setRadio(turnOn);
729 }
730
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700731 /**
732 * Used to notice when the calling process dies so we can self-expire
733 *
734 * Also used to know if the process has cleaned up after itself when
735 * our auto-expire timer goes off. The timer has a link to an object.
736 *
737 */
Robert Greenwalt42acef32009-08-12 16:08:25 -0700738 private class FeatureUser implements IBinder.DeathRecipient {
739 int mNetworkType;
740 String mFeature;
741 IBinder mBinder;
742 int mPid;
743 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -0800744 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700745
746 FeatureUser(int type, String feature, IBinder binder) {
747 super();
748 mNetworkType = type;
749 mFeature = feature;
750 mBinder = binder;
751 mPid = getCallingPid();
752 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -0800753 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700754
Robert Greenwalt42acef32009-08-12 16:08:25 -0700755 try {
756 mBinder.linkToDeath(this, 0);
757 } catch (RemoteException e) {
758 binderDied();
759 }
760 }
761
762 void unlinkDeathRecipient() {
763 mBinder.unlinkToDeath(this, 0);
764 }
765
766 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800767 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800768 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
769 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700770 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700771 }
772
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700773 public void expire() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800774 log("ConnectivityService FeatureUser expire(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800775 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
776 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700777 stopUsingNetworkFeature(this, false);
778 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800779
780 public String toString() {
781 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
782 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
783 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700784 }
785
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700786 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700787 public int startUsingNetworkFeature(int networkType, String feature,
788 IBinder binder) {
789 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800790 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700793 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700794 mNetConfigs[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700795 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700797
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700798 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700799
800 // TODO - move this into the MobileDataStateTracker
801 int usedNetworkType = networkType;
802 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville2b8bcfe2011-02-24 17:58:51 -0800803 usedNetworkType = convertFeatureToNetworkType(feature);
804 if (usedNetworkType < 0) {
805 Slog.e(TAG, "Can't match any netTracker!");
806 usedNetworkType = networkType;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700807 }
808 }
Robert Greenwalt50393202011-06-21 17:26:14 -0700809
810 if (mProtectedNetworks.contains(usedNetworkType)) {
811 enforceConnectivityInternalPermission();
812 }
813
Robert Greenwalt42acef32009-08-12 16:08:25 -0700814 NetworkStateTracker network = mNetTrackers[usedNetworkType];
815 if (network != null) {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800816 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt42acef32009-08-12 16:08:25 -0700817 if (usedNetworkType != networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700818 NetworkStateTracker radio = mNetTrackers[networkType];
819 NetworkInfo ni = network.getNetworkInfo();
820
821 if (ni.isAvailable() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800822 if (DBG) log("special network not available");
Robert Greenwalte32e8122010-12-29 14:35:21 -0800823 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
824 return Phone.APN_TYPE_NOT_AVAILABLE;
825 } else {
826 // else make the attempt anyway - probably giving REQUEST_STARTED below
827 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700828 }
829
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700830 synchronized(this) {
831 mFeatureUsers.add(f);
832 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
833 // this gets used for per-pid dns when connected
834 mNetRequestersPids[usedNetworkType].add(currentPid);
835 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700836 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700837
Robert Greenwaltf2102f72011-05-03 19:02:44 -0700838 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
839
840 if (restoreTimer >= 0) {
841 mHandler.sendMessageDelayed(
842 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
843 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700844
Robert Greenwalta64bf832009-08-19 20:19:33 -0700845 if ((ni.isConnectedOrConnecting() == true) &&
846 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700847 if (ni.isConnected() == true) {
848 // add the pid-specific dns
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -0700849 handleDnsConfigurationChange(networkType);
Wink Savilleed9c02b2010-12-03 12:01:38 -0800850 if (DBG) log("special network already active");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700851 return Phone.APN_ALREADY_ACTIVE;
852 }
Wink Savilleed9c02b2010-12-03 12:01:38 -0800853 if (DBG) log("special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700854 return Phone.APN_REQUEST_STARTED;
855 }
856
857 // check if the radio in play can make another contact
858 // assume if cannot for now
859
Wink Savilleed9c02b2010-12-03 12:01:38 -0800860 if (DBG) log("reconnecting to special network");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700861 network.reconnect();
862 return Phone.APN_REQUEST_STARTED;
863 } else {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800864 // need to remember this unsupported request so we respond appropriately on stop
865 synchronized(this) {
866 mFeatureUsers.add(f);
867 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
868 // this gets used for per-pid dns when connected
869 mNetRequestersPids[usedNetworkType].add(currentPid);
870 }
871 }
Robert Greenwalt02648a42010-05-18 10:52:51 -0700872 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700873 }
874 }
875 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 }
877
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700878 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700880 enforceChangePermission();
881
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700882 int pid = getCallingPid();
883 int uid = getCallingUid();
884
885 FeatureUser u = null;
886 boolean found = false;
887
888 synchronized(this) {
889 for (int i = 0; i < mFeatureUsers.size() ; i++) {
890 u = (FeatureUser)mFeatureUsers.get(i);
891 if (uid == u.mUid && pid == u.mPid &&
892 networkType == u.mNetworkType &&
893 TextUtils.equals(feature, u.mFeature)) {
894 found = true;
895 break;
896 }
897 }
898 }
899 if (found && u != null) {
900 // stop regardless of how many other time this proc had called start
901 return stopUsingNetworkFeature(u, true);
902 } else {
903 // none found!
Wink Savilleed9c02b2010-12-03 12:01:38 -0800904 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700905 return 1;
906 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700907 }
908
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700909 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
910 int networkType = u.mNetworkType;
911 String feature = u.mFeature;
912 int pid = u.mPid;
913 int uid = u.mUid;
914
915 NetworkStateTracker tracker = null;
916 boolean callTeardown = false; // used to carry our decision outside of sync block
917
Robert Greenwalt42acef32009-08-12 16:08:25 -0700918 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800919 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt42acef32009-08-12 16:08:25 -0700920 ": " + feature);
921 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
924 return -1;
925 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700926
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700927 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
928 // sync block
929 synchronized(this) {
930 // check if this process still has an outstanding start request
931 if (!mFeatureUsers.contains(u)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800932 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700933 return 1;
934 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700935 u.unlinkDeathRecipient();
936 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
937 // If we care about duplicate requests, check for that here.
938 //
939 // This is done to support the extension of a request - the app
940 // can request we start the network feature again and renew the
941 // auto-shutoff delay. Normal "stop" calls from the app though
942 // do not pay attention to duplicate requests - in effect the
943 // API does not refcount and a single stop will counter multiple starts.
944 if (ignoreDups == false) {
945 for (int i = 0; i < mFeatureUsers.size() ; i++) {
946 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
947 if (x.mUid == u.mUid && x.mPid == u.mPid &&
948 x.mNetworkType == u.mNetworkType &&
949 TextUtils.equals(x.mFeature, u.mFeature)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800950 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700951 return 1;
952 }
953 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700954 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700955
956 // TODO - move to MobileDataStateTracker
957 int usedNetworkType = networkType;
958 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville2b8bcfe2011-02-24 17:58:51 -0800959 usedNetworkType = convertFeatureToNetworkType(feature);
960 if (usedNetworkType < 0) {
961 usedNetworkType = networkType;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700962 }
963 }
964 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700965 if (tracker == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800966 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700967 return -1;
968 }
969 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700970 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700971 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -0800972 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700973 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800974 if (DBG) log("not tearing down special network - " +
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700975 "others still using it");
976 return 1;
977 }
978 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -0800979 } else {
980 if (DBG) log("not a known feature - dropping");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700981 }
982 }
Wink Savilleed9c02b2010-12-03 12:01:38 -0800983 if (DBG) log("Doing network teardown");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700984 if (callTeardown) {
985 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700986 return 1;
987 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -0700988 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 }
991
992 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700993 * @deprecated use requestRouteToHostAddress instead
994 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 * Ensure that a network route exists to deliver traffic to the specified
996 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700997 * @param networkType the type of the network over which traffic to the
998 * specified host is to be routed
999 * @param hostAddress the IP address of the host to which the route is
1000 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 * @return {@code true} on success, {@code false} on failure
1002 */
1003 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001004 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1005
1006 if (inetAddress == null) {
1007 return false;
1008 }
1009
1010 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1011 }
1012
1013 /**
1014 * Ensure that a network route exists to deliver traffic to the specified
1015 * host via the specified network interface.
1016 * @param networkType the type of the network over which traffic to the
1017 * specified host is to be routed
1018 * @param hostAddress the IP address of the host to which the route is
1019 * desired
1020 * @return {@code true} on success, {@code false} on failure
1021 */
1022 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001024 if (mProtectedNetworks.contains(networkType)) {
1025 enforceConnectivityInternalPermission();
1026 }
1027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1029 return false;
1030 }
1031 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001032
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001033 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1034 tracker.isTeardownRequested()) {
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001035 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001036 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001037 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001038 }
1039 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001041 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001042 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001043 return addHostRoute(tracker, addr, 0);
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001044 } catch (UnknownHostException e) {}
1045 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001046 }
1047
1048 /**
1049 * Ensure that a network route exists to deliver traffic to the specified
1050 * host via the mobile data network.
1051 * @param hostAddress the IP address of the host to which the route is desired,
1052 * in network byte order.
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001053 * TODO - deprecate
Irfan Sheriffd649c122010-06-09 15:39:36 -07001054 * @return {@code true} on success, {@code false} on failure
1055 */
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001056 private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress, int cycleCount) {
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001057 LinkProperties lp = nt.getLinkProperties();
1058 if ((lp == null) || (hostAddress == null)) return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001059
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001060 String interfaceName = lp.getInterfaceName();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001061 if (DBG) {
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001062 log("Requested host route to " + hostAddress + "(" + interfaceName + "), cycleCount=" +
1063 cycleCount);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001064 }
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001065 if (interfaceName == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001066 if (DBG) loge("addHostRoute failed due to null interface name");
Irfan Sheriffd649c122010-06-09 15:39:36 -07001067 return false;
1068 }
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001069
1070 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), hostAddress);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001071 InetAddress gatewayAddress = null;
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001072 if (bestRoute != null) {
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001073 gatewayAddress = bestRoute.getGateway();
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001074 // if the best route is ourself, don't relf-reference, just add the host route
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001075 if (hostAddress.equals(gatewayAddress)) gatewayAddress = null;
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001076 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001077 if (gatewayAddress != null) {
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001078 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1079 loge("Error adding hostroute - too much recursion");
1080 return false;
1081 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001082 if (!addHostRoute(nt, gatewayAddress, cycleCount+1)) return false;
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001083 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001084
1085 RouteInfo route = RouteInfo.makeHostRoute(hostAddress, gatewayAddress);
1086
1087 try {
1088 mNetd.addRoute(interfaceName, route);
1089 return true;
1090 } catch (Exception ex) {
1091 return false;
1092 }
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001093 }
1094
1095 // TODO support the removal of single host routes. Keep a ref count of them so we
1096 // aren't over-zealous
1097 private boolean removeHostRoute(NetworkStateTracker nt, InetAddress hostAddress) {
1098 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 }
1100
1101 /**
1102 * @see ConnectivityManager#getBackgroundDataSetting()
1103 */
1104 public boolean getBackgroundDataSetting() {
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001105 return mBackgroundDataEnabled.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 /**
1109 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1110 */
1111 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1112 mContext.enforceCallingOrSelfPermission(
1113 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1114 "ConnectivityService");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001115
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001116 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1117
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001118 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1119 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001122 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwaltdb4afae2011-02-25 13:44:09 -08001123 Settings.Secure.putInt(mContext.getContentResolver(),
1124 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1125 Intent broadcast = new Intent(
1126 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1127 mContext.sendBroadcast(broadcast);
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001128 }
1129
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001130 /**
1131 * @see ConnectivityManager#getMobileDataEnabled()
1132 */
1133 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001134 // TODO: This detail should probably be in DataConnectionTracker's
1135 // which is where we store the value and maybe make this
1136 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001137 enforceAccessPermission();
1138 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1139 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savilleed9c02b2010-12-03 12:01:38 -08001140 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001141 return retVal;
1142 }
1143
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001144 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001145 enforceConnectivityInternalPermission();
1146
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001147 if (DBG) {
1148 log("setDataDependency(" + networkType + ", " + met + ")");
1149 }
1150 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1151 (met ? ENABLED : DISABLED), networkType));
1152 }
1153
1154 private void handleSetDependencyMet(int networkType, boolean met) {
1155 if (mNetTrackers[networkType] != null) {
1156 if (DBG) {
1157 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1158 }
1159 mNetTrackers[networkType].setDependencyMet(met);
1160 }
1161 }
1162
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001163 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1164 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001165 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001166 // only someone like NPMS should only be calling us
Jeff Sharkey1a303952011-06-16 13:04:20 -07001167 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001168
1169 if (LOGD_RULES) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001170 Slog.d(TAG, "onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001171 }
1172
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001173 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001174 // skip update when we've already applied rules
1175 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1176 if (oldRules == uidRules) return;
1177
1178 mUidRules.put(uid, uidRules);
1179 }
1180
1181 // TODO: dispatch into NMS to push rules towards kernel module
1182 // TODO: notify UID when it has requested targeted updates
1183 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001184
1185 @Override
1186 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1187 // only someone like NPMS should only be calling us
1188 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1189
1190 if (LOGD_RULES) {
1191 Slog.d(TAG,
1192 "onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1193 }
1194
1195 synchronized (mRulesLock) {
1196 mMeteredIfaces.clear();
1197 for (String iface : meteredIfaces) {
1198 mMeteredIfaces.add(iface);
1199 }
1200 }
1201 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001202 };
1203
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001204 /**
1205 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1206 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001207 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001208 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001209 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001210
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001211 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001212 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001213 }
1214
1215 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001216 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1217 if (DBG) {
1218 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001219 }
Wink Savillee7982682010-12-07 10:31:02 -08001220 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001221 }
1222 }
1223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001225 mContext.enforceCallingOrSelfPermission(
1226 android.Manifest.permission.ACCESS_NETWORK_STATE,
1227 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 }
1229
1230 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001231 mContext.enforceCallingOrSelfPermission(
1232 android.Manifest.permission.CHANGE_NETWORK_STATE,
1233 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 }
1235
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001236 // TODO Make this a special check when it goes public
1237 private void enforceTetherChangePermission() {
1238 mContext.enforceCallingOrSelfPermission(
1239 android.Manifest.permission.CHANGE_NETWORK_STATE,
1240 "ConnectivityService");
1241 }
1242
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001243 private void enforceTetherAccessPermission() {
1244 mContext.enforceCallingOrSelfPermission(
1245 android.Manifest.permission.ACCESS_NETWORK_STATE,
1246 "ConnectivityService");
1247 }
1248
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001249 private void enforceConnectivityInternalPermission() {
1250 mContext.enforceCallingOrSelfPermission(
1251 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1252 "ConnectivityService");
1253 }
1254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001256 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1257 * network, we ignore it. If it is for the active network, we send out a
1258 * broadcast. But first, we check whether it might be possible to connect
1259 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 * @param info the {@code NetworkInfo} for the network
1261 */
1262 private void handleDisconnect(NetworkInfo info) {
1263
Robert Greenwalt42acef32009-08-12 16:08:25 -07001264 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265
Robert Greenwalt42acef32009-08-12 16:08:25 -07001266 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 /*
1268 * If the disconnected network is not the active one, then don't report
1269 * this as a loss of connectivity. What probably happened is that we're
1270 * getting the disconnect for a network that we explicitly disabled
1271 * in accordance with network preference policies.
1272 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001273 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001274 List pids = mNetRequestersPids[prevNetType];
1275 for (int i = 0; i<pids.size(); i++) {
1276 Integer pid = (Integer)pids.get(i);
1277 // will remove them because the net's no longer connected
1278 // need to do this now as only now do we know the pids and
1279 // can properly null things that are no longer referenced.
1280 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 }
1283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1285 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1286 if (info.isFailover()) {
1287 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1288 info.setFailover(false);
1289 }
1290 if (info.getReason() != null) {
1291 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1292 }
1293 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001294 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1295 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001297
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001298 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001299 tryFailover(prevNetType);
1300 if (mActiveDefaultNetwork != -1) {
1301 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001302 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1303 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001304 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001305 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1306 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001307 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001308 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001309
1310 // Reset interface if no other connections are using the same interface
1311 boolean doReset = true;
1312 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1313 if (linkProperties != null) {
1314 String oldIface = linkProperties.getInterfaceName();
1315 if (TextUtils.isEmpty(oldIface) == false) {
1316 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1317 if (networkStateTracker == null) continue;
1318 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1319 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1320 LinkProperties l = networkStateTracker.getLinkProperties();
1321 if (l == null) continue;
1322 if (oldIface.equals(l.getInterfaceName())) {
1323 doReset = false;
1324 break;
1325 }
1326 }
1327 }
1328 }
1329 }
1330
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001331 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001332 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001333
1334 sendStickyBroadcast(intent);
1335 /*
1336 * If the failover network is already connected, then immediately send
1337 * out a followup broadcast indicating successful failover
1338 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001339 if (mActiveDefaultNetwork != -1) {
1340 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001341 }
1342 }
1343
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001344 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001345 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001346 * If this is a default network, check if other defaults are available.
1347 * Try to reconnect on all available and let them hash it out when
1348 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001349 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001350 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001351 if (mActiveDefaultNetwork == prevNetType) {
1352 mActiveDefaultNetwork = -1;
1353 }
1354
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001355 // don't signal a reconnect for anything lower or equal priority than our
1356 // current connected default
1357 // TODO - don't filter by priority now - nice optimization but risky
1358// int currentPriority = -1;
1359// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001360// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001361// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001362 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001363 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001364 if (mNetConfigs[checkType] == null) continue;
1365 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001366
1367// Enabling the isAvailable() optimization caused mobile to not get
1368// selected if it was in the middle of error handling. Specifically
1369// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1370// would not be available and we wouldn't get connected to anything.
1371// So removing the isAvailable() optimization below for now. TODO: This
1372// optimization should work and we need to investigate why it doesn't work.
1373// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1374// complete before it is really complete.
1375// if (!mNetTrackers[checkType].isAvailable()) continue;
1376
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001377// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001378
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001379 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1380 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1381 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1382 checkInfo.setFailover(true);
1383 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001384 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001385 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 }
1389
1390 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001391 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1392 }
1393
1394 private void sendInetConditionBroadcast(NetworkInfo info) {
1395 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1396 }
1397
1398 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1399 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1401 if (info.isFailover()) {
1402 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1403 info.setFailover(false);
1404 }
1405 if (info.getReason() != null) {
1406 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1407 }
1408 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001409 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1410 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001412 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001413 sendStickyBroadcast(intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
1415
1416 /**
1417 * Called when an attempt to fail over to another network has failed.
1418 * @param info the {@link NetworkInfo} for the failed network
1419 */
1420 private void handleConnectionFailure(NetworkInfo info) {
1421 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422
Robert Greenwalt42acef32009-08-12 16:08:25 -07001423 String reason = info.getReason();
1424 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001425
Robert Greenwalt572172b2010-10-08 16:35:52 -07001426 String reasonText;
1427 if (reason == null) {
1428 reasonText = ".";
1429 } else {
1430 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001432 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001433
1434 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1435 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1436 if (getActiveNetworkInfo() == null) {
1437 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1438 }
1439 if (reason != null) {
1440 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1441 }
1442 if (extraInfo != null) {
1443 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1444 }
1445 if (info.isFailover()) {
1446 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1447 info.setFailover(false);
1448 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001449
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001450 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001451 tryFailover(info.getType());
1452 if (mActiveDefaultNetwork != -1) {
1453 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001454 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1455 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001456 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001457 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1458 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001459 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001460
Robert Greenwalt029be812010-09-20 18:01:43 -07001461 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001462 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001463 /*
1464 * If the failover network is already connected, then immediately send
1465 * out a followup broadcast indicating successful failover
1466 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001467 if (mActiveDefaultNetwork != -1) {
1468 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001469 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001470 }
1471
1472 private void sendStickyBroadcast(Intent intent) {
1473 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001474 if (!mSystemReady) {
1475 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001476 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001477 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1478 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001479 }
1480 }
1481
1482 void systemReady() {
1483 synchronized(this) {
1484 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001485 if (mInitialBroadcast != null) {
1486 mContext.sendStickyBroadcast(mInitialBroadcast);
1487 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001488 }
1489 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001490 // load the global proxy at startup
1491 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
1493
1494 private void handleConnect(NetworkInfo info) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001495 int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496
1497 // snapshot isFailover, because sendConnectedBroadcast() resets it
1498 boolean isFailover = info.isFailover();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001499 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500
Robert Greenwalt42acef32009-08-12 16:08:25 -07001501 // if this is a default net and other default is running
1502 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001503 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001504 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1505 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001506 mNetConfigs[mActiveDefaultNetwork].priority >
1507 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001508 mNetworkPreference == mActiveDefaultNetwork) {
1509 // don't accept this one
Wink Savilleed9c02b2010-12-03 12:01:38 -08001510 if (DBG) {
1511 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001512 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001513 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001514 teardown(thisNet);
1515 return;
1516 } else {
1517 // tear down the other
1518 NetworkStateTracker otherNet =
1519 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001520 if (DBG) {
1521 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001522 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001523 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001524 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001525 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07001526 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001527 return;
1528 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001529 }
1530 }
1531 synchronized (ConnectivityService.this) {
1532 // have a new default network, release the transition wakelock in a second
1533 // if it's held. The second pause is to allow apps to reconnect over the
1534 // new network
1535 if (mNetTransitionWakeLock.isHeld()) {
1536 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001537 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001538 mNetTransitionWakeLockSerialNumber, 0),
1539 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001540 }
1541 }
1542 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001543 // this will cause us to come up initially as unconnected and switching
1544 // to connected after our normal pause unless somebody reports us as reall
1545 // disconnected
1546 mDefaultInetConditionPublished = 0;
1547 mDefaultConnectionSequence++;
1548 mInetConditionChangeInFlight = false;
1549 // Don't do this - if we never sign in stay, grey
1550 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001553 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001554 handleConnectivityChange(type, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001555 sendConnectedBroadcast(info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 }
1557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001559 * After a change in the connectivity state of a network. We're mainly
1560 * concerned with making sure that the list of DNS servers is set up
1561 * according to which networks are connected, and ensuring that the
1562 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001564 private void handleConnectivityChange(int netType, boolean doReset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001566 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001567 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001569 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001570
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001571 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001572 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07001573 handleApplyDefaultProxy(netType);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001574 addDefaultRoute(mNetTrackers[netType]);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001575 } else {
Robert Greenwalt13ec4062011-04-01 10:51:22 -07001576 // many radios add a default route even when we don't want one.
1577 // remove the default route unless we need it for our active network
1578 if (mActiveDefaultNetwork != -1) {
1579 LinkProperties defaultLinkProperties =
1580 mNetTrackers[mActiveDefaultNetwork].getLinkProperties();
1581 LinkProperties newLinkProperties =
1582 mNetTrackers[netType].getLinkProperties();
1583 String defaultIface = defaultLinkProperties.getInterfaceName();
1584 if (defaultIface != null &&
1585 !defaultIface.equals(newLinkProperties.getInterfaceName())) {
1586 removeDefaultRoute(mNetTrackers[netType]);
1587 }
1588 }
Michael Jurka8fad7ee2011-03-30 19:54:08 -07001589 addPrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001590 }
1591 } else {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001592 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001593 removeDefaultRoute(mNetTrackers[netType]);
1594 } else {
1595 removePrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07001598
1599 if (doReset) {
1600 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1601 if (linkProperties != null) {
1602 String iface = linkProperties.getInterfaceName();
1603 if (TextUtils.isEmpty(iface) == false) {
1604 if (DBG) log("resetConnections(" + iface + ")");
1605 NetworkUtils.resetConnections(iface);
1606 }
1607 }
1608 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001609
1610 // TODO: Temporary notifying upstread change to Tethering.
1611 // @see bug/4455071
1612 /** Notify TetheringService if interface name has been changed. */
1613 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1614 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1615 if (isTetheringSupported()) {
1616 mTethering.handleTetherIfaceChange();
1617 }
1618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 }
1620
Irfan Sheriffd649c122010-06-09 15:39:36 -07001621 private void addPrivateDnsRoutes(NetworkStateTracker nt) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07001622 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001623 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001624 if (p == null) return;
1625 String interfaceName = p.getInterfaceName();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001626
1627 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001628 log("addPrivateDnsRoutes for " + nt +
Irfan Sheriffd649c122010-06-09 15:39:36 -07001629 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1630 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001631 if (interfaceName != null && !privateDnsRouteSet) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001632 Collection<InetAddress> dnsList = p.getDnses();
1633 for (InetAddress dns : dnsList) {
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001634 addHostRoute(nt, dns, 0);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001635 }
1636 nt.privateDnsRouteSet(true);
1637 }
1638 }
1639
1640 private void removePrivateDnsRoutes(NetworkStateTracker nt) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001641 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001642 if (p == null) return;
1643 String interfaceName = p.getInterfaceName();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001644 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1645 if (interfaceName != null && privateDnsRouteSet) {
1646 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001647 log("removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
Irfan Sheriffd649c122010-06-09 15:39:36 -07001648 " (" + interfaceName + ")");
1649 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001650
1651 Collection<InetAddress> dnsList = p.getDnses();
1652 for (InetAddress dns : dnsList) {
1653 if (DBG) log(" removing " + dns);
1654 RouteInfo route = RouteInfo.makeHostRoute(dns);
1655 try {
1656 mNetd.removeRoute(interfaceName, route);
1657 } catch (Exception ex) {
1658 loge("error (" + ex + ") removing dns route " + route);
1659 }
1660 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001661 nt.privateDnsRouteSet(false);
1662 }
1663 }
1664
Irfan Sheriffd649c122010-06-09 15:39:36 -07001665
1666 private void addDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001667 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001668 if (p == null) return;
1669 String interfaceName = p.getInterfaceName();
Robert Greenwalt992564e2011-02-09 13:56:06 -08001670 if (TextUtils.isEmpty(interfaceName)) return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001671
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001672 for (RouteInfo route : p.getRoutes()) {
Robert Greenwaltaa70f102011-04-28 14:28:50 -07001673 //TODO - handle non-default routes
1674 if (route.isDefaultRoute()) {
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001675 if (DBG) log("adding default route " + route);
Robert Greenwaltaa70f102011-04-28 14:28:50 -07001676 InetAddress gateway = route.getGateway();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001677 if (addHostRoute(nt, gateway, 0)) {
1678 try {
1679 mNetd.addRoute(interfaceName, route);
1680 } catch (Exception e) {
1681 loge("error adding default route " + route);
1682 continue;
1683 }
Robert Greenwaltaa70f102011-04-28 14:28:50 -07001684 if (DBG) {
1685 NetworkInfo networkInfo = nt.getNetworkInfo();
1686 log("addDefaultRoute for " + networkInfo.getTypeName() +
1687 " (" + interfaceName + "), GatewayAddr=" +
1688 gateway.getHostAddress());
1689 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001690 } else {
1691 loge("error adding host route for default route " + route);
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07001692 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001693 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001694 }
1695 }
1696
1697
1698 public void removeDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001699 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001700 if (p == null) return;
1701 String interfaceName = p.getInterfaceName();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001702
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001703 if (interfaceName == null) return;
1704
1705 for (RouteInfo route : p.getRoutes()) {
1706 //TODO - handle non-default routes
1707 if (route.isDefaultRoute()) {
1708 try {
1709 mNetd.removeRoute(interfaceName, route);
1710 } catch (Exception ex) {
1711 loge("error (" + ex + ") removing default route " + route);
1712 continue;
1713 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07001714 if (DBG) {
1715 NetworkInfo networkInfo = nt.getNetworkInfo();
1716 log("removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1717 interfaceName + ")");
1718 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001719 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001720 }
1721 }
1722
1723 /**
1724 * Reads the network specific TCP buffer sizes from SystemProperties
1725 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1726 * wide use
1727 */
1728 public void updateNetworkSettings(NetworkStateTracker nt) {
1729 String key = nt.getTcpBufferSizesPropName();
1730 String bufferSizes = SystemProperties.get(key);
1731
1732 if (bufferSizes.length() == 0) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001733 loge(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07001734
1735 // Setting to default values so we won't be stuck to previous values
1736 key = "net.tcp.buffersize.default";
1737 bufferSizes = SystemProperties.get(key);
1738 }
1739
1740 // Set values in kernel
1741 if (bufferSizes.length() != 0) {
1742 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001743 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07001744 + "] which comes from [" + key + "]");
1745 }
1746 setBufferSize(bufferSizes);
1747 }
1748 }
1749
1750 /**
1751 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1752 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1753 *
1754 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1755 * writeMin, writeInitial, writeMax"
1756 */
1757 private void setBufferSize(String bufferSizes) {
1758 try {
1759 String[] values = bufferSizes.split(",");
1760
1761 if (values.length == 6) {
1762 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04001763 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1764 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1765 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1766 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1767 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1768 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001769 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001770 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001771 }
1772 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001773 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001774 }
1775 }
1776
Robert Greenwalt42acef32009-08-12 16:08:25 -07001777 /**
1778 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1779 * on the highest priority active net which this process requested.
1780 * If there aren't any, clear it out
1781 */
1782 private void reassessPidDns(int myPid, boolean doBump)
1783 {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001784 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001785 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001786 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001787 continue;
1788 }
1789 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001790 if (nt.getNetworkInfo().isConnected() &&
1791 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001792 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001793 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001794 List pids = mNetRequestersPids[i];
1795 for (int j=0; j<pids.size(); j++) {
1796 Integer pid = (Integer)pids.get(j);
1797 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001798 Collection<InetAddress> dnses = p.getDnses();
1799 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001800 if (doBump) {
1801 bumpDns();
1802 }
1803 return;
1804 }
1805 }
1806 }
1807 }
1808 // nothing found - delete
1809 for (int i = 1; ; i++) {
1810 String prop = "net.dns" + i + "." + myPid;
1811 if (SystemProperties.get(prop).length() == 0) {
1812 if (doBump) {
1813 bumpDns();
1814 }
1815 return;
1816 }
1817 SystemProperties.set(prop, "");
1818 }
1819 }
1820
Robert Greenwalt10398722010-12-17 15:20:36 -08001821 // return true if results in a change
1822 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001823 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08001824 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001825 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001826 String dnsString = dns.getHostAddress();
1827 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1828 changed = true;
1829 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1830 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001831 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001832 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001833 }
1834
1835 private void bumpDns() {
1836 /*
1837 * Bump the property that tells the name resolver library to reread
1838 * the DNS server list from the properties.
1839 */
1840 String propVal = SystemProperties.get("net.dnschange");
1841 int n = 0;
1842 if (propVal.length() != 0) {
1843 try {
1844 n = Integer.parseInt(propVal);
1845 } catch (NumberFormatException e) {}
1846 }
1847 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07001848 /*
1849 * Tell the VMs to toss their DNS caches
1850 */
1851 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1852 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001853 /*
1854 * Connectivity events can happen before boot has completed ...
1855 */
1856 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07001857 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001858 }
1859
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001860 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001861 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001862 NetworkStateTracker nt = mNetTrackers[netType];
1863 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001864 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001865 if (p == null) return;
1866 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08001867 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001868 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001869 int j = 1;
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001870 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001871 String dnsString = mDefaultDns.getHostAddress();
1872 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1873 if (DBG) {
1874 log("no dns provided - using " + dnsString);
1875 }
1876 changed = true;
1877 SystemProperties.set("net.dns1", dnsString);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001878 }
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001879 j++;
1880 } else {
1881 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001882 String dnsString = dns.getHostAddress();
1883 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1884 j++;
1885 continue;
1886 }
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001887 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001888 log("adding dns " + dns + " for " +
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001889 nt.getNetworkInfo().getTypeName());
1890 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001891 changed = true;
1892 SystemProperties.set("net.dns" + j++, dnsString);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001893 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001894 }
1895 for (int k=j ; k<mNumDnsEntries; k++) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001896 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1897 if (DBG) log("erasing net.dns" + k);
1898 changed = true;
1899 SystemProperties.set("net.dns" + k, "");
1900 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001901 }
1902 mNumDnsEntries = j;
1903 } else {
1904 // set per-pid dns for attached secondary nets
1905 List pids = mNetRequestersPids[netType];
1906 for (int y=0; y< pids.size(); y++) {
1907 Integer pid = (Integer)pids.get(y);
Robert Greenwalt10398722010-12-17 15:20:36 -08001908 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
1910 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001911 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001913 }
1914
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001915 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001916 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1917 NETWORK_RESTORE_DELAY_PROP_NAME);
1918 if(restoreDefaultNetworkDelayStr != null &&
1919 restoreDefaultNetworkDelayStr.length() != 0) {
1920 try {
1921 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1922 } catch (NumberFormatException e) {
1923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001925 // if the system property isn't set, use the value for the apn type
1926 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1927
1928 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1929 (mNetConfigs[networkType] != null)) {
1930 ret = mNetConfigs[networkType].restoreTime;
1931 }
1932 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 }
1934
1935 @Override
1936 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001937 if (mContext.checkCallingOrSelfPermission(
1938 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001940 pw.println("Permission Denial: can't dump ConnectivityService " +
1941 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1942 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 return;
1944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 pw.println();
1946 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08001947 if (nst != null) {
1948 if (nst.getNetworkInfo().isConnected()) {
1949 pw.println("Active network: " + nst.getNetworkInfo().
1950 getTypeName());
1951 }
1952 pw.println(nst.getNetworkInfo());
1953 pw.println(nst);
1954 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001957
1958 pw.println("Network Requester Pids:");
1959 for (int net : mPriorityList) {
1960 String pidString = net + ": ";
1961 for (Object pid : mNetRequestersPids[net]) {
1962 pidString = pidString + pid.toString() + ", ";
1963 }
1964 pw.println(pidString);
1965 }
1966 pw.println();
1967
1968 pw.println("FeatureUsers:");
1969 for (Object requester : mFeatureUsers) {
1970 pw.println(requester.toString());
1971 }
1972 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001973
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001974 synchronized (this) {
1975 pw.println("NetworkTranstionWakeLock is currently " +
1976 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1977 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1978 }
1979 pw.println();
1980
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001981 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001982
1983 if (mInetLog != null) {
1984 pw.println();
1985 pw.println("Inet condition reports:");
1986 for(int i = 0; i < mInetLog.size(); i++) {
1987 pw.println(mInetLog.get(i));
1988 }
1989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 }
1991
Robert Greenwalt42acef32009-08-12 16:08:25 -07001992 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07001994 public MyHandler(Looper looper) {
1995 super(looper);
1996 }
1997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 @Override
1999 public void handleMessage(Message msg) {
2000 NetworkInfo info;
2001 switch (msg.what) {
2002 case NetworkStateTracker.EVENT_STATE_CHANGED:
2003 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002004 int type = info.getType();
2005 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002006
Wink Savilleed9c02b2010-12-03 12:01:38 -08002007 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002008 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002009 state + "/" + info.getDetailedState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010
2011 // Connectivity state changed:
2012 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002013 // [12-9] Network subtype (for mobile network, as defined
2014 // by TelephonyManager)
2015 // [8-3] Detailed state ordinal (as defined by
2016 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 // [2-0] Network type (as defined by ConnectivityManager)
2018 int eventLogParam = (info.getType() & 0x7) |
2019 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2020 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002021 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002022 eventLogParam);
2023
2024 if (info.getDetailedState() ==
2025 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002027 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002029 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002031 // the logic here is, handle SUSPENDED the same as
2032 // DISCONNECTED. The only difference being we are
2033 // broadcasting an intent with NetworkInfo that's
2034 // suspended. This allows the applications an
2035 // opportunity to handle DISCONNECTED and SUSPENDED
2036 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002038 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 handleConnect(info);
2040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002043 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002044 // TODO: Temporary allowing network configuration
2045 // change not resetting sockets.
2046 // @see bug/4455071
2047 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002049 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002050 String causedBy = null;
2051 synchronized (ConnectivityService.this) {
2052 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2053 mNetTransitionWakeLock.isHeld()) {
2054 mNetTransitionWakeLock.release();
2055 causedBy = mNetTransitionWakeLockCausedBy;
2056 }
2057 }
2058 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002059 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002060 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002061 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002062 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002063 FeatureUser u = (FeatureUser)msg.obj;
2064 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002065 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002066 case EVENT_INET_CONDITION_CHANGE:
2067 {
2068 int netType = msg.arg1;
2069 int condition = msg.arg2;
2070 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002071 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002072 }
2073 case EVENT_INET_CONDITION_HOLD_END:
2074 {
2075 int netType = msg.arg1;
2076 int sequence = msg.arg2;
2077 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002078 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002079 }
2080 case EVENT_SET_NETWORK_PREFERENCE:
2081 {
2082 int preference = msg.arg1;
2083 handleSetNetworkPreference(preference);
2084 break;
2085 }
2086 case EVENT_SET_BACKGROUND_DATA:
2087 {
2088 boolean enabled = (msg.arg1 == ENABLED);
2089 handleSetBackgroundData(enabled);
2090 break;
2091 }
2092 case EVENT_SET_MOBILE_DATA:
2093 {
2094 boolean enabled = (msg.arg1 == ENABLED);
2095 handleSetMobileData(enabled);
2096 break;
2097 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002098 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2099 {
2100 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002101 break;
2102 }
2103 case EVENT_SET_DEPENDENCY_MET:
2104 {
2105 boolean met = (msg.arg1 == ENABLED);
2106 handleSetDependencyMet(msg.arg2, met);
2107 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 }
2110 }
2111 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002112
2113 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002114 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002115 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002116
2117 if (isTetheringSupported()) {
2118 return mTethering.tether(iface);
2119 } else {
2120 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2121 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002122 }
2123
2124 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002125 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002126 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002127
2128 if (isTetheringSupported()) {
2129 return mTethering.untether(iface);
2130 } else {
2131 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2132 }
2133 }
2134
2135 // javadoc from interface
2136 public int getLastTetherError(String iface) {
2137 enforceTetherAccessPermission();
2138
2139 if (isTetheringSupported()) {
2140 return mTethering.getLastTetherError(iface);
2141 } else {
2142 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2143 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002144 }
2145
2146 // TODO - proper iface API for selection by property, inspection, etc
2147 public String[] getTetherableUsbRegexs() {
2148 enforceTetherAccessPermission();
2149 if (isTetheringSupported()) {
2150 return mTethering.getTetherableUsbRegexs();
2151 } else {
2152 return new String[0];
2153 }
2154 }
2155
2156 public String[] getTetherableWifiRegexs() {
2157 enforceTetherAccessPermission();
2158 if (isTetheringSupported()) {
2159 return mTethering.getTetherableWifiRegexs();
2160 } else {
2161 return new String[0];
2162 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002163 }
2164
Danica Chang6fdd0c62010-08-11 14:54:43 -07002165 public String[] getTetherableBluetoothRegexs() {
2166 enforceTetherAccessPermission();
2167 if (isTetheringSupported()) {
2168 return mTethering.getTetherableBluetoothRegexs();
2169 } else {
2170 return new String[0];
2171 }
2172 }
2173
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002174 // TODO - move iface listing, queries, etc to new module
2175 // javadoc from interface
2176 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002177 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002178 return mTethering.getTetherableIfaces();
2179 }
2180
2181 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002182 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002183 return mTethering.getTetheredIfaces();
2184 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002185
Robert Greenwalt5a735062010-03-02 17:25:02 -08002186 public String[] getTetheringErroredIfaces() {
2187 enforceTetherAccessPermission();
2188 return mTethering.getErroredIfaces();
2189 }
2190
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002191 // if ro.tether.denied = true we default to no tethering
2192 // gservices could set the secure setting to 1 though to enable it on a build where it
2193 // had previously been turned off.
2194 public boolean isTetheringSupported() {
2195 enforceTetherAccessPermission();
2196 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002197 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2198 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2199 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002200 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002201
2202 // An API NetworkStateTrackers can call when they lose their network.
2203 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2204 // whichever happens first. The timer is started by the first caller and not
2205 // restarted by subsequent callers.
2206 public void requestNetworkTransitionWakelock(String forWhom) {
2207 enforceConnectivityInternalPermission();
2208 synchronized (this) {
2209 if (mNetTransitionWakeLock.isHeld()) return;
2210 mNetTransitionWakeLockSerialNumber++;
2211 mNetTransitionWakeLock.acquire();
2212 mNetTransitionWakeLockCausedBy = forWhom;
2213 }
2214 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002215 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002216 mNetTransitionWakeLockSerialNumber, 0),
2217 mNetTransitionWakeLockTimeout);
2218 return;
2219 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002220
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002221 // 100 percent is full good, 0 is full bad.
2222 public void reportInetCondition(int networkType, int percentage) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002223 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002224 mContext.enforceCallingOrSelfPermission(
2225 android.Manifest.permission.STATUS_BAR,
2226 "ConnectivityService");
2227
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002228 if (DBG) {
2229 int pid = getCallingPid();
2230 int uid = getCallingUid();
2231 String s = pid + "(" + uid + ") reports inet is " +
2232 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2233 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2234 mInetLog.add(s);
2235 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2236 mInetLog.remove(0);
2237 }
2238 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002239 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002240 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2241 }
2242
2243 private void handleInetConditionChange(int netType, int condition) {
2244 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002245 log("Inet connectivity change, net=" +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002246 netType + ", condition=" + condition +
2247 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2248 }
2249 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002250 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002251 return;
2252 }
2253 if (mActiveDefaultNetwork != netType) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002254 if (DBG) log("given net not default - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002255 return;
2256 }
2257 mDefaultInetCondition = condition;
2258 int delay;
2259 if (mInetConditionChangeInFlight == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002260 if (DBG) log("starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002261 // setup a new hold to debounce this
2262 if (mDefaultInetCondition > 50) {
2263 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2264 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2265 } else {
2266 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2267 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2268 }
2269 mInetConditionChangeInFlight = true;
2270 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2271 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2272 } else {
2273 // we've set the new condition, when this hold ends that will get
2274 // picked up
Wink Savilleed9c02b2010-12-03 12:01:38 -08002275 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002276 }
2277 }
2278
2279 private void handleInetConditionHoldEnd(int netType, int sequence) {
2280 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002281 log("Inet hold end, net=" + netType +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002282 ", condition =" + mDefaultInetCondition +
2283 ", published condition =" + mDefaultInetConditionPublished);
2284 }
2285 mInetConditionChangeInFlight = false;
2286
2287 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002288 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002289 return;
2290 }
2291 if (mDefaultConnectionSequence != sequence) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002292 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002293 return;
2294 }
2295 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002296 if (DBG) log("no change in condition - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002297 return;
2298 }
2299 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2300 if (networkInfo.isConnected() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002301 if (DBG) log("default network not connected - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002302 return;
2303 }
2304 mDefaultInetConditionPublished = mDefaultInetCondition;
2305 sendInetConditionBroadcast(networkInfo);
2306 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002307 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002308
2309 public synchronized ProxyProperties getProxy() {
2310 if (mGlobalProxy != null) return mGlobalProxy;
2311 if (mDefaultProxy != null) return mDefaultProxy;
2312 return null;
2313 }
2314
2315 public void setGlobalProxy(ProxyProperties proxyProperties) {
2316 enforceChangePermission();
2317 synchronized (mGlobalProxyLock) {
2318 if (proxyProperties == mGlobalProxy) return;
2319 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2320 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2321
2322 String host = "";
2323 int port = 0;
2324 String exclList = "";
2325 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2326 mGlobalProxy = new ProxyProperties(proxyProperties);
2327 host = mGlobalProxy.getHost();
2328 port = mGlobalProxy.getPort();
2329 exclList = mGlobalProxy.getExclusionList();
2330 } else {
2331 mGlobalProxy = null;
2332 }
2333 ContentResolver res = mContext.getContentResolver();
2334 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2335 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002336 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002337 exclList);
2338 }
2339
2340 if (mGlobalProxy == null) {
2341 proxyProperties = mDefaultProxy;
2342 }
2343 sendProxyBroadcast(proxyProperties);
2344 }
2345
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002346 private void loadGlobalProxy() {
2347 ContentResolver res = mContext.getContentResolver();
2348 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2349 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2350 String exclList = Settings.Secure.getString(res,
2351 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2352 if (!TextUtils.isEmpty(host)) {
2353 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2354 synchronized (mGlobalProxyLock) {
2355 mGlobalProxy = proxyProperties;
2356 }
2357 }
2358 }
2359
Robert Greenwalt434203a2010-10-11 16:00:27 -07002360 public ProxyProperties getGlobalProxy() {
2361 synchronized (mGlobalProxyLock) {
2362 return mGlobalProxy;
2363 }
2364 }
2365
2366 private void handleApplyDefaultProxy(int type) {
2367 // check if new default - push it out to all VM if so
2368 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2369 synchronized (this) {
2370 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2371 if (mDefaultProxy == proxy) return;
2372 if (!TextUtils.isEmpty(proxy.getHost())) {
2373 mDefaultProxy = proxy;
2374 } else {
2375 mDefaultProxy = null;
2376 }
2377 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002378 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002379 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2380 if (mGlobalProxy != null) return;
2381 sendProxyBroadcast(proxy);
2382 }
2383
2384 private void handleDeprecatedGlobalHttpProxy() {
2385 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2386 Settings.Secure.HTTP_PROXY);
2387 if (!TextUtils.isEmpty(proxy)) {
2388 String data[] = proxy.split(":");
2389 String proxyHost = data[0];
2390 int proxyPort = 8080;
2391 if (data.length > 1) {
2392 try {
2393 proxyPort = Integer.parseInt(data[1]);
2394 } catch (NumberFormatException e) {
2395 return;
2396 }
2397 }
2398 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2399 setGlobalProxy(p);
2400 }
2401 }
2402
2403 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002404 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002405 log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002406 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002407 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2408 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002409 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002410 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002411 }
2412
2413 private static class SettingsObserver extends ContentObserver {
2414 private int mWhat;
2415 private Handler mHandler;
2416 SettingsObserver(Handler handler, int what) {
2417 super(handler);
2418 mHandler = handler;
2419 mWhat = what;
2420 }
2421
2422 void observe(Context context) {
2423 ContentResolver resolver = context.getContentResolver();
2424 resolver.registerContentObserver(Settings.Secure.getUriFor(
2425 Settings.Secure.HTTP_PROXY), false, this);
2426 }
2427
2428 @Override
2429 public void onChange(boolean selfChange) {
2430 mHandler.obtainMessage(mWhat).sendToTarget();
2431 }
2432 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002433
2434 private void log(String s) {
2435 Slog.d(TAG, s);
2436 }
2437
2438 private void loge(String s) {
2439 Slog.e(TAG, s);
2440 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002441
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002442 int convertFeatureToNetworkType(String feature){
2443 int networkType = -1;
2444 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2445 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2446 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2447 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2448 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2449 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2450 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2451 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2452 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2453 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2454 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2455 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2456 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2457 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2458 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2459 }
2460 return networkType;
2461 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002462
2463 private static <T> T checkNotNull(T value, String message) {
2464 if (value == null) {
2465 throw new NullPointerException(message);
2466 }
2467 return value;
2468 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002469
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002470 /**
2471 * Protect a socket from VPN routing rules. This method is used by
2472 * VpnBuilder and not available in ConnectivityManager. Permission
2473 * checks are done in Vpn class.
2474 * @hide
2475 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002476 @Override
2477 public void protectVpn(ParcelFileDescriptor socket) {
2478 mVpn.protect(socket, getDefaultInterface());
2479 }
2480
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002481 /**
2482 * Prepare for a VPN application. This method is used by VpnDialogs
2483 * and not available in ConnectivityManager. Permission checks are
2484 * done in Vpn class.
2485 * @hide
2486 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002487 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002488 public boolean prepareVpn(String oldPackage, String newPackage) {
2489 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002490 }
2491
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002492 /**
2493 * Configure a TUN interface and return its file descriptor. Parameters
2494 * are encoded and opaque to this class. This method is used by VpnBuilder
2495 * and not available in ConnectivityManager. Permission checks are done
2496 * in Vpn class.
2497 * @hide
2498 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002499 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002500 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002501 return mVpn.establish(config);
2502 }
2503
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002504 /**
2505 * Handle a legacy VPN request.
2506 * @hide
2507 */
2508 @Override
2509 public void doLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2510 mVpn.doLegacyVpn(config, racoon, mtpd);
2511 }
2512
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002513 private String getDefaultInterface() {
2514 if (ConnectivityManager.isNetworkTypeValid(mActiveDefaultNetwork)) {
2515 NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
2516 if (tracker != null) {
2517 LinkProperties properties = tracker.getLinkProperties();
2518 if (properties != null) {
2519 return properties.getInterfaceName();
2520 }
2521 }
2522 }
2523 throw new IllegalStateException("No default interface");
2524 }
2525
2526 /**
2527 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2528 * through NetworkStateTracker since it works differently. For example, it
2529 * needs to override DNS servers but never takes the default routes. It
2530 * relies on another data network, and it could keep existing connections
2531 * alive after reconnecting, switching between networks, or even resuming
2532 * from deep sleep. Calls from applications should be done synchronously
2533 * to avoid race conditions. As these are all hidden APIs, refactoring can
2534 * be done whenever a better abstraction is developed.
2535 */
2536 public class VpnCallback {
2537
2538 private VpnCallback() {
2539 }
2540
Chia-chi Yeh8909b102011-07-01 01:09:42 -07002541 public synchronized void override(List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002542 // TODO: override DNS servers and http proxy.
2543 }
2544
2545 public synchronized void restore() {
2546 // TODO: restore VPN changes.
2547 }
2548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549}