blob: 663f4f47f56ea325a2789d1795fb7a2fea679fc0 [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;
Hung-ying Tyan6b818de2011-01-19 16:48:38 +080047import android.net.vpn.VpnManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.net.wifi.WifiStateTracker;
49import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040050import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070052import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070053import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070054import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Looper;
56import android.os.Message;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070057import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070058import android.os.PowerManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070059import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.os.ServiceManager;
61import android.os.SystemProperties;
62import android.provider.Settings;
Robert Greenwalt42acef32009-08-12 16:08:25 -070063import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080065import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070066import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070068import com.android.internal.net.VpnConfig;
Robert Greenwalt42acef32009-08-12 16:08:25 -070069import com.android.internal.telephony.Phone;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080070import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070071import com.android.server.connectivity.Vpn;
72
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070073import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070074import com.google.android.collect.Sets;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -070077import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import java.io.PrintWriter;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070079import java.net.InetAddress;
80import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -070081import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070082import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070083import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -070084import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070085import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -070086import java.util.List;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070087import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088
89/**
90 * @hide
91 */
92public class ConnectivityService extends IConnectivityManager.Stub {
93
Robert Greenwaltba175a52010-10-05 19:12:26 -070094 private static final boolean DBG = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095 private static final String TAG = "ConnectivityService";
96
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070097 private static final boolean LOGD_RULES = false;
98
Robert Greenwalt42acef32009-08-12 16:08:25 -070099 // how long to wait before switching back to a radio's default network
100 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
101 // system property that can override the above value
102 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
103 "android.telephony.apn-restore";
104
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700105 // used in recursive route setting to add gateways for the host for which
106 // a host route was requested.
107 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
108
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800109 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800110 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800111
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700112 private Vpn mVpn;
113
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700114 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
115 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700116 /** Currently active network rules by UID. */
117 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700118 /** Set of ifaces that are costly. */
119 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 /**
122 * Sometimes we want to refer to the individual network state
123 * trackers separately, and sometimes we just want to treat them
124 * abstractly.
125 */
126 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700127
128 /**
129 * A per Net list of the PID's that requested access to the net
130 * used both as a refcount and for per-PID DNS selection
131 */
132 private List mNetRequestersPids[];
133
Robert Greenwalt42acef32009-08-12 16:08:25 -0700134 // priority order of the nettrackers
135 // (excluding dynamically set mNetworkPreference)
136 // TODO - move mNetworkTypePreference into this
137 private int[] mPriorityList;
138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 private Context mContext;
140 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700141 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700142 // 0 is full bad, 100 is full good
143 private int mDefaultInetCondition = 0;
144 private int mDefaultInetConditionPublished = 0;
145 private boolean mInetConditionChangeInFlight = false;
146 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147
148 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
150 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700151 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152
Robert Greenwaltd825ea42010-12-29 16:15:02 -0800153 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
154
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700155 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700156 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700157
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700158 private static final int ENABLED = 1;
159 private static final int DISABLED = 0;
160
161 // Share the event space with NetworkStateTracker (which can't see this
162 // internal class but sends us events). If you change these, change
163 // NetworkStateTracker.java too.
164 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
165 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
166
167 /**
168 * used internally as a delayed event to make us switch back to the
169 * default network
170 */
171 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
172 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
173
174 /**
175 * used internally to change our mobile data enabled flag
176 */
177 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
178 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
179
180 /**
181 * used internally to change our network preference setting
182 * arg1 = networkType to prefer
183 */
184 private static final int EVENT_SET_NETWORK_PREFERENCE =
185 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
186
187 /**
188 * used internally to synchronize inet condition reports
189 * arg1 = networkType
190 * arg2 = condition (0 bad, 100 good)
191 */
192 private static final int EVENT_INET_CONDITION_CHANGE =
193 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
194
195 /**
196 * used internally to mark the end of inet condition hold periods
197 * arg1 = networkType
198 */
199 private static final int EVENT_INET_CONDITION_HOLD_END =
200 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
201
202 /**
203 * used internally to set the background data preference
204 * arg1 = TRUE for enabled, FALSE for disabled
205 */
206 private static final int EVENT_SET_BACKGROUND_DATA =
207 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
208
209 /**
210 * used internally to set enable/disable cellular data
211 * arg1 = ENBALED or DISABLED
212 */
213 private static final int EVENT_SET_MOBILE_DATA =
214 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
215
Robert Greenwaltf3331232010-09-24 14:32:21 -0700216 /**
217 * used internally to clear a wakelock when transitioning
218 * from one net to another
219 */
220 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
221 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
222
Robert Greenwalt434203a2010-10-11 16:00:27 -0700223 /**
224 * used internally to reload global proxy settings
225 */
226 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
227 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
228
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700229 /**
230 * used internally to set external dependency met/unmet
231 * arg1 = ENABLED (met) or DISABLED (unmet)
232 * arg2 = NetworkType
233 */
234 private static final int EVENT_SET_DEPENDENCY_MET =
235 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
236
Robert Greenwalt42acef32009-08-12 16:08:25 -0700237 private Handler mHandler;
238
239 // list of DeathRecipients used to make sure features are turned off when
240 // a process dies
241 private List mFeatureUsers;
242
Mike Lockwood0f79b542009-08-14 14:18:49 -0400243 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800244 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400245
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700246 private PowerManager.WakeLock mNetTransitionWakeLock;
247 private String mNetTransitionWakeLockCausedBy = "";
248 private int mNetTransitionWakeLockSerialNumber;
249 private int mNetTransitionWakeLockTimeout;
250
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700251 private InetAddress mDefaultDns;
252
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700253 // used in DBG mode to track inet condition reports
254 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
255 private ArrayList mInetLog;
256
Robert Greenwalt434203a2010-10-11 16:00:27 -0700257 // track the current default http proxy - tell the world if we get a new one (real change)
258 private ProxyProperties mDefaultProxy = null;
259 // track the global proxy.
260 private ProxyProperties mGlobalProxy = null;
261 private final Object mGlobalProxyLock = new Object();
262
263 private SettingsObserver mSettingsObserver;
264
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700265 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700266 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700267
Robert Greenwalt511288a2009-12-07 11:33:18 -0800268 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700269 public int mSimultaneity;
270 public int mType;
271 public RadioAttributes(String init) {
272 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700273 mType = Integer.parseInt(fragments[0]);
274 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700275 }
276 }
277 RadioAttributes[] mRadioAttributes;
278
Robert Greenwalt50393202011-06-21 17:26:14 -0700279 // the set of network types that can only be enabled by system/sig apps
280 List mProtectedNetworks;
281
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700282 public ConnectivityService(
283 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800284 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800285
Wink Savillebb08caf2010-09-02 19:23:52 -0700286 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
287 handlerThread.start();
288 mHandler = new MyHandler(handlerThread.getLooper());
289
Robert Greenwaltd825ea42010-12-29 16:15:02 -0800290 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
291 Settings.Secure.BACKGROUND_DATA, 1) == 1);
292
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800293 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800294 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
295 String id = Settings.Secure.getString(context.getContentResolver(),
296 Settings.Secure.ANDROID_ID);
297 if (id != null && id.length() > 0) {
298 String name = new String("android_").concat(id);
299 SystemProperties.set("net.hostname", name);
300 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800301 }
302
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700303 // read our default dns server ip
304 String dns = Settings.Secure.getString(context.getContentResolver(),
305 Settings.Secure.DEFAULT_DNS_SERVER);
306 if (dns == null || dns.length() == 0) {
307 dns = context.getResources().getString(
308 com.android.internal.R.string.config_default_dns_server);
309 }
310 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800311 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
312 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800313 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700314 }
315
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700316 mContext = checkNotNull(context, "missing Context");
317 mNetd = checkNotNull(netd, "missing INetworkManagementService");
318 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700319
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700320 try {
321 mPolicyManager.registerListener(mPolicyListener);
322 } catch (RemoteException e) {
323 // ouch, no rules updates means some processes may never get network
324 Slog.e(TAG, "unable to register INetworkPolicyListener", e);
325 }
326
327 final PowerManager powerManager = (PowerManager) context.getSystemService(
328 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700329 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
330 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
331 com.android.internal.R.integer.config_networkTransitionTimeout);
332
Robert Greenwalt42acef32009-08-12 16:08:25 -0700333 mNetTrackers = new NetworkStateTracker[
334 ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700337
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700338 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700339 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700340
Robert Greenwalt42acef32009-08-12 16:08:25 -0700341 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700342 String[] raStrings = context.getResources().getStringArray(
343 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700344 for (String raString : raStrings) {
345 RadioAttributes r = new RadioAttributes(raString);
346 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800347 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700348 continue;
349 }
350 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800351 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700352 r.mType);
353 continue;
354 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700355 mRadioAttributes[r.mType] = r;
356 }
357
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700358 String[] naStrings = context.getResources().getStringArray(
359 com.android.internal.R.array.networkAttributes);
360 for (String naString : naStrings) {
361 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700362 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700363 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800364 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700365 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700366 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700367 }
Wink Saville975c8482011-04-07 14:23:45 -0700368 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800369 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700370 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700371 continue;
372 }
Wink Saville975c8482011-04-07 14:23:45 -0700373 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800374 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700375 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700376 continue;
377 }
Wink Saville975c8482011-04-07 14:23:45 -0700378 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700379 mNetworksDefined++;
380 } catch(Exception e) {
381 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700382 }
383 }
384
Robert Greenwalt50393202011-06-21 17:26:14 -0700385 mProtectedNetworks = new ArrayList<Integer>();
386 int[] protectedNetworks = context.getResources().getIntArray(
387 com.android.internal.R.array.config_protectedNetworks);
388 for (int p : protectedNetworks) {
389 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
390 mProtectedNetworks.add(p);
391 } else {
392 if (DBG) loge("Ignoring protectedNetwork " + p);
393 }
394 }
395
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700396 // high priority first
397 mPriorityList = new int[mNetworksDefined];
398 {
399 int insertionPoint = mNetworksDefined-1;
400 int currentLowest = 0;
401 int nextLowest = 0;
402 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700403 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700404 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700405 if (na.priority < currentLowest) continue;
406 if (na.priority > currentLowest) {
407 if (na.priority < nextLowest || nextLowest == 0) {
408 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700409 }
410 continue;
411 }
Wink Saville975c8482011-04-07 14:23:45 -0700412 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700413 }
414 currentLowest = nextLowest;
415 nextLowest = 0;
416 }
417 }
418
419 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
420 for (int i : mPriorityList) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700421 mNetRequestersPids[i] = new ArrayList();
422 }
423
424 mFeatureUsers = new ArrayList();
425
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700426 mNumDnsEntries = 0;
427
428 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
429 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 /*
431 * Create the network state trackers for Wi-Fi and mobile
432 * data. Maybe this could be done with a factory class,
433 * but it's not clear that it's worth it, given that
434 * the number of different network types is not going
435 * to change very often.
436 */
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700437 for (int netType : mPriorityList) {
Wink Saville975c8482011-04-07 14:23:45 -0700438 switch (mNetConfigs[netType].radio) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700439 case ConnectivityManager.TYPE_WIFI:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800440 if (DBG) log("Starting Wifi Service.");
Wink Savillec7a98342010-08-13 16:11:42 -0700441 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff0d255342010-07-28 09:35:20 -0700442 WifiService wifiService = new WifiService(context);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700443 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff0d255342010-07-28 09:35:20 -0700444 wifiService.checkAndStartWifi();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700445 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Savillec7a98342010-08-13 16:11:42 -0700446 wst.startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700447 break;
448 case ConnectivityManager.TYPE_MOBILE:
Wink Savillec7a98342010-08-13 16:11:42 -0700449 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700450 mNetConfigs[netType].name);
Wink Savillec7a98342010-08-13 16:11:42 -0700451 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700452 break;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800453 case ConnectivityManager.TYPE_DUMMY:
454 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700455 mNetConfigs[netType].name);
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800456 mNetTrackers[netType].startMonitoring(context, mHandler);
457 break;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800458 case ConnectivityManager.TYPE_BLUETOOTH:
459 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
460 mNetTrackers[netType].startMonitoring(context, mHandler);
461 break;
Benoit Goby19970692010-12-22 14:29:40 -0800462 case ConnectivityManager.TYPE_ETHERNET:
463 mNetTrackers[netType] = EthernetDataTracker.getInstance();
464 mNetTrackers[netType].startMonitoring(context, mHandler);
465 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700466 default:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800467 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Saville975c8482011-04-07 14:23:45 -0700468 mNetConfigs[netType].radio);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700469 continue;
470 }
471 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800472
Chia-chi Yehc9338302011-05-11 16:35:13 -0700473 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
474 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
475
476 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700477 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700478 mTethering.getTetherableWifiRegexs().length != 0 ||
479 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700480 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800481
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700482 mVpn = new Vpn(mContext, new VpnCallback());
483
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700484 try {
485 nmService.registerObserver(mTethering);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700486 nmService.registerObserver(mVpn);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700487 } catch (RemoteException e) {
488 loge("Error registering observer :" + e);
489 }
490
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700491 if (DBG) {
492 mInetLog = new ArrayList();
493 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700494
495 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
496 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800497
498 loadGlobalProxy();
Hung-ying Tyan6b818de2011-01-19 16:48:38 +0800499
500 VpnManager.startVpnService(context);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 }
502
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700505 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 * @param preference the new preference
507 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700508 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700510
511 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 }
513
514 public int getNetworkPreference() {
515 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700516 int preference;
517 synchronized(this) {
518 preference = mNetworkPreference;
519 }
520 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 }
522
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700523 private void handleSetNetworkPreference(int preference) {
524 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700525 mNetConfigs[preference] != null &&
526 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700527 if (mNetworkPreference != preference) {
528 final ContentResolver cr = mContext.getContentResolver();
529 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
530 synchronized(this) {
531 mNetworkPreference = preference;
532 }
533 enforcePreference();
534 }
535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 private int getPersistedNetworkPreference() {
539 final ContentResolver cr = mContext.getContentResolver();
540
541 final int networkPrefSetting = Settings.Secure
542 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
543 if (networkPrefSetting != -1) {
544 return networkPrefSetting;
545 }
546
547 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
548 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700551 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 * In this method, we only tear down a non-preferred network. Establishing
553 * a connection to the preferred network is taken care of when we handle
554 * the disconnect event from the non-preferred network
555 * (see {@link #handleDisconnect(NetworkInfo)}).
556 */
557 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700558 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 return;
560
Robert Greenwalt42acef32009-08-12 16:08:25 -0700561 if (!mNetTrackers[mNetworkPreference].isAvailable())
562 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563
Robert Greenwalt42acef32009-08-12 16:08:25 -0700564 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700565 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700566 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700567 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800568 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700569 " in enforcePreference");
570 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700571 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 }
573 }
574 }
575
576 private boolean teardown(NetworkStateTracker netTracker) {
577 if (netTracker.teardown()) {
578 netTracker.setTeardownRequested(true);
579 return true;
580 } else {
581 return false;
582 }
583 }
584
585 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700586 * Check if UID should be blocked from using the network represented by the
587 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700588 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700589 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
590 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700591
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700592 final boolean networkCostly;
593 final int uidRules;
594 synchronized (mRulesLock) {
595 networkCostly = mMeteredIfaces.contains(iface);
596 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700597 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700598
599 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
600 return true;
601 }
602
603 // no restrictive rules; network is visible
604 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700605 }
606
607 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700608 * Return a filtered {@link NetworkInfo}, potentially marked
609 * {@link DetailedState#BLOCKED} based on
610 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700611 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700612 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
613 NetworkInfo info = tracker.getNetworkInfo();
614 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700615 // network is blocked; clone and override state
616 info = new NetworkInfo(info);
617 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700618 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700619 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700620 }
621
622 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 * Return NetworkInfo for the active (i.e., connected) network interface.
624 * It is assumed that at most one network is active at a time. If more
625 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700626 * @return the info for the active network, or {@code null} if none is
627 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700629 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700631 enforceAccessPermission();
632 final int uid = Binder.getCallingUid();
633 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 }
635
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700636 @Override
637 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
638 enforceConnectivityInternalPermission();
639 return getNetworkInfo(mActiveDefaultNetwork, uid);
640 }
641
642 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 public NetworkInfo getNetworkInfo(int networkType) {
644 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700645 final int uid = Binder.getCallingUid();
646 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 }
648
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700649 private NetworkInfo getNetworkInfo(int networkType, int uid) {
650 NetworkInfo info = null;
651 if (isNetworkTypeValid(networkType)) {
652 final NetworkStateTracker tracker = mNetTrackers[networkType];
653 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700654 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700655 }
656 }
657 return info;
658 }
659
660 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 public NetworkInfo[] getAllNetworkInfo() {
662 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700663 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700664 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700665 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700666 for (NetworkStateTracker tracker : mNetTrackers) {
667 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700668 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700669 }
670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700672 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 }
674
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700675 /**
676 * Return LinkProperties for the active (i.e., connected) default
677 * network interface. It is assumed that at most one default network
678 * is active at a time. If more than one is active, it is indeterminate
679 * which will be returned.
680 * @return the ip properties for the active network, or {@code null} if
681 * none is active
682 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700683 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700684 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700685 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700686 }
687
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700688 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700689 public LinkProperties getLinkProperties(int networkType) {
690 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700691 if (isNetworkTypeValid(networkType)) {
692 final NetworkStateTracker tracker = mNetTrackers[networkType];
693 if (tracker != null) {
694 return tracker.getLinkProperties();
695 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700696 }
697 return null;
698 }
699
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700700 @Override
701 public NetworkState[] getAllNetworkState() {
702 enforceAccessPermission();
703 final int uid = Binder.getCallingUid();
704 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700705 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700706 for (NetworkStateTracker tracker : mNetTrackers) {
707 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700708 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700709 result.add(new NetworkState(
710 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
711 }
712 }
713 }
714 return result.toArray(new NetworkState[result.size()]);
715 }
716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 public boolean setRadios(boolean turnOn) {
718 boolean result = true;
719 enforceChangePermission();
720 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700721 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 }
723 return result;
724 }
725
726 public boolean setRadio(int netType, boolean turnOn) {
727 enforceChangePermission();
728 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
729 return false;
730 }
731 NetworkStateTracker tracker = mNetTrackers[netType];
732 return tracker != null && tracker.setRadio(turnOn);
733 }
734
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700735 /**
736 * Used to notice when the calling process dies so we can self-expire
737 *
738 * Also used to know if the process has cleaned up after itself when
739 * our auto-expire timer goes off. The timer has a link to an object.
740 *
741 */
Robert Greenwalt42acef32009-08-12 16:08:25 -0700742 private class FeatureUser implements IBinder.DeathRecipient {
743 int mNetworkType;
744 String mFeature;
745 IBinder mBinder;
746 int mPid;
747 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -0800748 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700749
750 FeatureUser(int type, String feature, IBinder binder) {
751 super();
752 mNetworkType = type;
753 mFeature = feature;
754 mBinder = binder;
755 mPid = getCallingPid();
756 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -0800757 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700758
Robert Greenwalt42acef32009-08-12 16:08:25 -0700759 try {
760 mBinder.linkToDeath(this, 0);
761 } catch (RemoteException e) {
762 binderDied();
763 }
764 }
765
766 void unlinkDeathRecipient() {
767 mBinder.unlinkToDeath(this, 0);
768 }
769
770 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800771 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800772 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
773 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700774 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700775 }
776
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700777 public void expire() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800778 log("ConnectivityService FeatureUser expire(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800779 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
780 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700781 stopUsingNetworkFeature(this, false);
782 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800783
784 public String toString() {
785 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
786 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
787 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700788 }
789
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700790 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700791 public int startUsingNetworkFeature(int networkType, String feature,
792 IBinder binder) {
793 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800794 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700797 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700798 mNetConfigs[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700799 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700801
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700802 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700803
804 // TODO - move this into the MobileDataStateTracker
805 int usedNetworkType = networkType;
806 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville2b8bcfe2011-02-24 17:58:51 -0800807 usedNetworkType = convertFeatureToNetworkType(feature);
808 if (usedNetworkType < 0) {
809 Slog.e(TAG, "Can't match any netTracker!");
810 usedNetworkType = networkType;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700811 }
812 }
Robert Greenwalt50393202011-06-21 17:26:14 -0700813
814 if (mProtectedNetworks.contains(usedNetworkType)) {
815 enforceConnectivityInternalPermission();
816 }
817
Robert Greenwalt42acef32009-08-12 16:08:25 -0700818 NetworkStateTracker network = mNetTrackers[usedNetworkType];
819 if (network != null) {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800820 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt42acef32009-08-12 16:08:25 -0700821 if (usedNetworkType != networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700822 NetworkStateTracker radio = mNetTrackers[networkType];
823 NetworkInfo ni = network.getNetworkInfo();
824
825 if (ni.isAvailable() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800826 if (DBG) log("special network not available");
Robert Greenwalte32e8122010-12-29 14:35:21 -0800827 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
828 return Phone.APN_TYPE_NOT_AVAILABLE;
829 } else {
830 // else make the attempt anyway - probably giving REQUEST_STARTED below
831 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700832 }
833
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700834 synchronized(this) {
835 mFeatureUsers.add(f);
836 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
837 // this gets used for per-pid dns when connected
838 mNetRequestersPids[usedNetworkType].add(currentPid);
839 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700840 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700841
Robert Greenwaltf2102f72011-05-03 19:02:44 -0700842 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
843
844 if (restoreTimer >= 0) {
845 mHandler.sendMessageDelayed(
846 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
847 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700848
Robert Greenwalta64bf832009-08-19 20:19:33 -0700849 if ((ni.isConnectedOrConnecting() == true) &&
850 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700851 if (ni.isConnected() == true) {
852 // add the pid-specific dns
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -0700853 handleDnsConfigurationChange(networkType);
Wink Savilleed9c02b2010-12-03 12:01:38 -0800854 if (DBG) log("special network already active");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700855 return Phone.APN_ALREADY_ACTIVE;
856 }
Wink Savilleed9c02b2010-12-03 12:01:38 -0800857 if (DBG) log("special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700858 return Phone.APN_REQUEST_STARTED;
859 }
860
861 // check if the radio in play can make another contact
862 // assume if cannot for now
863
Wink Savilleed9c02b2010-12-03 12:01:38 -0800864 if (DBG) log("reconnecting to special network");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700865 network.reconnect();
866 return Phone.APN_REQUEST_STARTED;
867 } else {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800868 // need to remember this unsupported request so we respond appropriately on stop
869 synchronized(this) {
870 mFeatureUsers.add(f);
871 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
872 // this gets used for per-pid dns when connected
873 mNetRequestersPids[usedNetworkType].add(currentPid);
874 }
875 }
Robert Greenwalt02648a42010-05-18 10:52:51 -0700876 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700877 }
878 }
879 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 }
881
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700882 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700884 enforceChangePermission();
885
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700886 int pid = getCallingPid();
887 int uid = getCallingUid();
888
889 FeatureUser u = null;
890 boolean found = false;
891
892 synchronized(this) {
893 for (int i = 0; i < mFeatureUsers.size() ; i++) {
894 u = (FeatureUser)mFeatureUsers.get(i);
895 if (uid == u.mUid && pid == u.mPid &&
896 networkType == u.mNetworkType &&
897 TextUtils.equals(feature, u.mFeature)) {
898 found = true;
899 break;
900 }
901 }
902 }
903 if (found && u != null) {
904 // stop regardless of how many other time this proc had called start
905 return stopUsingNetworkFeature(u, true);
906 } else {
907 // none found!
Wink Savilleed9c02b2010-12-03 12:01:38 -0800908 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700909 return 1;
910 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700911 }
912
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700913 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
914 int networkType = u.mNetworkType;
915 String feature = u.mFeature;
916 int pid = u.mPid;
917 int uid = u.mUid;
918
919 NetworkStateTracker tracker = null;
920 boolean callTeardown = false; // used to carry our decision outside of sync block
921
Robert Greenwalt42acef32009-08-12 16:08:25 -0700922 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800923 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt42acef32009-08-12 16:08:25 -0700924 ": " + feature);
925 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
928 return -1;
929 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700930
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700931 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
932 // sync block
933 synchronized(this) {
934 // check if this process still has an outstanding start request
935 if (!mFeatureUsers.contains(u)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800936 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700937 return 1;
938 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700939 u.unlinkDeathRecipient();
940 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
941 // If we care about duplicate requests, check for that here.
942 //
943 // This is done to support the extension of a request - the app
944 // can request we start the network feature again and renew the
945 // auto-shutoff delay. Normal "stop" calls from the app though
946 // do not pay attention to duplicate requests - in effect the
947 // API does not refcount and a single stop will counter multiple starts.
948 if (ignoreDups == false) {
949 for (int i = 0; i < mFeatureUsers.size() ; i++) {
950 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
951 if (x.mUid == u.mUid && x.mPid == u.mPid &&
952 x.mNetworkType == u.mNetworkType &&
953 TextUtils.equals(x.mFeature, u.mFeature)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800954 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700955 return 1;
956 }
957 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700958 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700959
960 // TODO - move to MobileDataStateTracker
961 int usedNetworkType = networkType;
962 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Saville2b8bcfe2011-02-24 17:58:51 -0800963 usedNetworkType = convertFeatureToNetworkType(feature);
964 if (usedNetworkType < 0) {
965 usedNetworkType = networkType;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700966 }
967 }
968 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700969 if (tracker == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800970 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700971 return -1;
972 }
973 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700974 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700975 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -0800976 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700977 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800978 if (DBG) log("not tearing down special network - " +
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700979 "others still using it");
980 return 1;
981 }
982 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -0800983 } else {
984 if (DBG) log("not a known feature - dropping");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700985 }
986 }
Wink Savilleed9c02b2010-12-03 12:01:38 -0800987 if (DBG) log("Doing network teardown");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700988 if (callTeardown) {
989 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700990 return 1;
991 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -0700992 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 }
995
996 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700997 * @deprecated use requestRouteToHostAddress instead
998 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 * Ensure that a network route exists to deliver traffic to the specified
1000 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001001 * @param networkType the type of the network over which traffic to the
1002 * specified host is to be routed
1003 * @param hostAddress the IP address of the host to which the route is
1004 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 * @return {@code true} on success, {@code false} on failure
1006 */
1007 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001008 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1009
1010 if (inetAddress == null) {
1011 return false;
1012 }
1013
1014 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1015 }
1016
1017 /**
1018 * Ensure that a network route exists to deliver traffic to the specified
1019 * host via the specified network interface.
1020 * @param networkType the type of the network over which traffic to the
1021 * specified host is to be routed
1022 * @param hostAddress the IP address of the host to which the route is
1023 * desired
1024 * @return {@code true} on success, {@code false} on failure
1025 */
1026 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001028 if (mProtectedNetworks.contains(networkType)) {
1029 enforceConnectivityInternalPermission();
1030 }
1031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1033 return false;
1034 }
1035 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001036
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001037 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1038 tracker.isTeardownRequested()) {
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001039 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001040 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001041 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001042 }
1043 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001045 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001046 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001047 return addHostRoute(tracker, addr, 0);
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001048 } catch (UnknownHostException e) {}
1049 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001050 }
1051
1052 /**
1053 * Ensure that a network route exists to deliver traffic to the specified
1054 * host via the mobile data network.
1055 * @param hostAddress the IP address of the host to which the route is desired,
1056 * in network byte order.
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001057 * TODO - deprecate
Irfan Sheriffd649c122010-06-09 15:39:36 -07001058 * @return {@code true} on success, {@code false} on failure
1059 */
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001060 private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress, int cycleCount) {
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001061 LinkProperties lp = nt.getLinkProperties();
1062 if ((lp == null) || (hostAddress == null)) return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001063
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001064 String interfaceName = lp.getInterfaceName();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001065 if (DBG) {
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001066 log("Requested host route to " + hostAddress + "(" + interfaceName + "), cycleCount=" +
1067 cycleCount);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001068 }
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001069 if (interfaceName == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001070 if (DBG) loge("addHostRoute failed due to null interface name");
Irfan Sheriffd649c122010-06-09 15:39:36 -07001071 return false;
1072 }
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001073
1074 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), hostAddress);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001075 InetAddress gatewayAddress = null;
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001076 if (bestRoute != null) {
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001077 gatewayAddress = bestRoute.getGateway();
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001078 // if the best route is ourself, don't relf-reference, just add the host route
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001079 if (hostAddress.equals(gatewayAddress)) gatewayAddress = null;
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001080 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001081 if (gatewayAddress != null) {
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001082 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1083 loge("Error adding hostroute - too much recursion");
1084 return false;
1085 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001086 if (!addHostRoute(nt, gatewayAddress, cycleCount+1)) return false;
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001087 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001088
1089 RouteInfo route = RouteInfo.makeHostRoute(hostAddress, gatewayAddress);
1090
1091 try {
1092 mNetd.addRoute(interfaceName, route);
1093 return true;
1094 } catch (Exception ex) {
1095 return false;
1096 }
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001097 }
1098
1099 // TODO support the removal of single host routes. Keep a ref count of them so we
1100 // aren't over-zealous
1101 private boolean removeHostRoute(NetworkStateTracker nt, InetAddress hostAddress) {
1102 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 }
1104
1105 /**
1106 * @see ConnectivityManager#getBackgroundDataSetting()
1107 */
1108 public boolean getBackgroundDataSetting() {
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001109 return mBackgroundDataEnabled.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 /**
1113 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1114 */
1115 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1116 mContext.enforceCallingOrSelfPermission(
1117 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1118 "ConnectivityService");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001119
Robert Greenwaltd825ea42010-12-29 16:15:02 -08001120 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1121
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001122 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1123 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001126 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwaltdb4afae2011-02-25 13:44:09 -08001127 Settings.Secure.putInt(mContext.getContentResolver(),
1128 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1129 Intent broadcast = new Intent(
1130 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1131 mContext.sendBroadcast(broadcast);
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001132 }
1133
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001134 /**
1135 * @see ConnectivityManager#getMobileDataEnabled()
1136 */
1137 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001138 // TODO: This detail should probably be in DataConnectionTracker's
1139 // which is where we store the value and maybe make this
1140 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001141 enforceAccessPermission();
1142 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1143 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savilleed9c02b2010-12-03 12:01:38 -08001144 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001145 return retVal;
1146 }
1147
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001148 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001149 enforceConnectivityInternalPermission();
1150
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001151 if (DBG) {
1152 log("setDataDependency(" + networkType + ", " + met + ")");
1153 }
1154 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1155 (met ? ENABLED : DISABLED), networkType));
1156 }
1157
1158 private void handleSetDependencyMet(int networkType, boolean met) {
1159 if (mNetTrackers[networkType] != null) {
1160 if (DBG) {
1161 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1162 }
1163 mNetTrackers[networkType].setDependencyMet(met);
1164 }
1165 }
1166
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001167 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1168 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001169 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001170 // only someone like NPMS should only be calling us
Jeff Sharkey1a303952011-06-16 13:04:20 -07001171 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001172
1173 if (LOGD_RULES) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001174 Slog.d(TAG, "onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001175 }
1176
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001177 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001178 // skip update when we've already applied rules
1179 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1180 if (oldRules == uidRules) return;
1181
1182 mUidRules.put(uid, uidRules);
1183 }
1184
1185 // TODO: dispatch into NMS to push rules towards kernel module
1186 // TODO: notify UID when it has requested targeted updates
1187 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001188
1189 @Override
1190 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1191 // only someone like NPMS should only be calling us
1192 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1193
1194 if (LOGD_RULES) {
1195 Slog.d(TAG,
1196 "onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1197 }
1198
1199 synchronized (mRulesLock) {
1200 mMeteredIfaces.clear();
1201 for (String iface : meteredIfaces) {
1202 mMeteredIfaces.add(iface);
1203 }
1204 }
1205 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001206 };
1207
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001208 /**
1209 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1210 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001211 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001212 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001213 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001214
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001215 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001216 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001217 }
1218
1219 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001220 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1221 if (DBG) {
1222 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001223 }
Wink Savillee7982682010-12-07 10:31:02 -08001224 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001225 }
1226 }
1227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001229 mContext.enforceCallingOrSelfPermission(
1230 android.Manifest.permission.ACCESS_NETWORK_STATE,
1231 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233
1234 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001235 mContext.enforceCallingOrSelfPermission(
1236 android.Manifest.permission.CHANGE_NETWORK_STATE,
1237 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 }
1239
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001240 // TODO Make this a special check when it goes public
1241 private void enforceTetherChangePermission() {
1242 mContext.enforceCallingOrSelfPermission(
1243 android.Manifest.permission.CHANGE_NETWORK_STATE,
1244 "ConnectivityService");
1245 }
1246
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001247 private void enforceTetherAccessPermission() {
1248 mContext.enforceCallingOrSelfPermission(
1249 android.Manifest.permission.ACCESS_NETWORK_STATE,
1250 "ConnectivityService");
1251 }
1252
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001253 private void enforceConnectivityInternalPermission() {
1254 mContext.enforceCallingOrSelfPermission(
1255 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1256 "ConnectivityService");
1257 }
1258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001260 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1261 * network, we ignore it. If it is for the active network, we send out a
1262 * broadcast. But first, we check whether it might be possible to connect
1263 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 * @param info the {@code NetworkInfo} for the network
1265 */
1266 private void handleDisconnect(NetworkInfo info) {
1267
Robert Greenwalt42acef32009-08-12 16:08:25 -07001268 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269
Robert Greenwalt42acef32009-08-12 16:08:25 -07001270 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 /*
1272 * If the disconnected network is not the active one, then don't report
1273 * this as a loss of connectivity. What probably happened is that we're
1274 * getting the disconnect for a network that we explicitly disabled
1275 * in accordance with network preference policies.
1276 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001277 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001278 List pids = mNetRequestersPids[prevNetType];
1279 for (int i = 0; i<pids.size(); i++) {
1280 Integer pid = (Integer)pids.get(i);
1281 // will remove them because the net's no longer connected
1282 // need to do this now as only now do we know the pids and
1283 // can properly null things that are no longer referenced.
1284 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 }
1287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1289 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1290 if (info.isFailover()) {
1291 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1292 info.setFailover(false);
1293 }
1294 if (info.getReason() != null) {
1295 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1296 }
1297 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001298 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1299 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001301
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001302 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001303 tryFailover(prevNetType);
1304 if (mActiveDefaultNetwork != -1) {
1305 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001306 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1307 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001308 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001309 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1310 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001311 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001312 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001313
1314 // Reset interface if no other connections are using the same interface
1315 boolean doReset = true;
1316 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1317 if (linkProperties != null) {
1318 String oldIface = linkProperties.getInterfaceName();
1319 if (TextUtils.isEmpty(oldIface) == false) {
1320 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1321 if (networkStateTracker == null) continue;
1322 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1323 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1324 LinkProperties l = networkStateTracker.getLinkProperties();
1325 if (l == null) continue;
1326 if (oldIface.equals(l.getInterfaceName())) {
1327 doReset = false;
1328 break;
1329 }
1330 }
1331 }
1332 }
1333 }
1334
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001335 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001336 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001337
1338 sendStickyBroadcast(intent);
1339 /*
1340 * If the failover network is already connected, then immediately send
1341 * out a followup broadcast indicating successful failover
1342 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001343 if (mActiveDefaultNetwork != -1) {
1344 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001345 }
1346 }
1347
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001348 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001349 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001350 * If this is a default network, check if other defaults are available.
1351 * Try to reconnect on all available and let them hash it out when
1352 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001353 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001354 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001355 if (mActiveDefaultNetwork == prevNetType) {
1356 mActiveDefaultNetwork = -1;
1357 }
1358
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001359 // don't signal a reconnect for anything lower or equal priority than our
1360 // current connected default
1361 // TODO - don't filter by priority now - nice optimization but risky
1362// int currentPriority = -1;
1363// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001364// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001365// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001366 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001367 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001368 if (mNetConfigs[checkType] == null) continue;
1369 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001370
1371// Enabling the isAvailable() optimization caused mobile to not get
1372// selected if it was in the middle of error handling. Specifically
1373// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1374// would not be available and we wouldn't get connected to anything.
1375// So removing the isAvailable() optimization below for now. TODO: This
1376// optimization should work and we need to investigate why it doesn't work.
1377// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1378// complete before it is really complete.
1379// if (!mNetTrackers[checkType].isAvailable()) continue;
1380
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001381// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001382
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001383 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1384 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1385 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1386 checkInfo.setFailover(true);
1387 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001388 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001389 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 }
1393
1394 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001395 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1396 }
1397
1398 private void sendInetConditionBroadcast(NetworkInfo info) {
1399 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1400 }
1401
1402 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1403 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1405 if (info.isFailover()) {
1406 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1407 info.setFailover(false);
1408 }
1409 if (info.getReason() != null) {
1410 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1411 }
1412 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001413 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1414 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001416 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001417 sendStickyBroadcast(intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419
1420 /**
1421 * Called when an attempt to fail over to another network has failed.
1422 * @param info the {@link NetworkInfo} for the failed network
1423 */
1424 private void handleConnectionFailure(NetworkInfo info) {
1425 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426
Robert Greenwalt42acef32009-08-12 16:08:25 -07001427 String reason = info.getReason();
1428 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001429
Robert Greenwalt572172b2010-10-08 16:35:52 -07001430 String reasonText;
1431 if (reason == null) {
1432 reasonText = ".";
1433 } else {
1434 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001436 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001437
1438 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1439 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1440 if (getActiveNetworkInfo() == null) {
1441 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1442 }
1443 if (reason != null) {
1444 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1445 }
1446 if (extraInfo != null) {
1447 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1448 }
1449 if (info.isFailover()) {
1450 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1451 info.setFailover(false);
1452 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001453
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001454 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001455 tryFailover(info.getType());
1456 if (mActiveDefaultNetwork != -1) {
1457 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001458 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1459 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001460 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001461 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1462 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001463 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001464
Robert Greenwalt029be812010-09-20 18:01:43 -07001465 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001466 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001467 /*
1468 * If the failover network is already connected, then immediately send
1469 * out a followup broadcast indicating successful failover
1470 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001471 if (mActiveDefaultNetwork != -1) {
1472 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001473 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001474 }
1475
1476 private void sendStickyBroadcast(Intent intent) {
1477 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001478 if (!mSystemReady) {
1479 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001480 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001481 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1482 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001483 }
1484 }
1485
1486 void systemReady() {
1487 synchronized(this) {
1488 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001489 if (mInitialBroadcast != null) {
1490 mContext.sendStickyBroadcast(mInitialBroadcast);
1491 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001492 }
1493 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001494 // load the global proxy at startup
1495 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 }
1497
1498 private void handleConnect(NetworkInfo info) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001499 int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500
1501 // snapshot isFailover, because sendConnectedBroadcast() resets it
1502 boolean isFailover = info.isFailover();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001503 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504
Robert Greenwalt42acef32009-08-12 16:08:25 -07001505 // if this is a default net and other default is running
1506 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001507 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001508 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1509 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001510 mNetConfigs[mActiveDefaultNetwork].priority >
1511 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001512 mNetworkPreference == mActiveDefaultNetwork) {
1513 // don't accept this one
Wink Savilleed9c02b2010-12-03 12:01:38 -08001514 if (DBG) {
1515 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001516 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001517 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001518 teardown(thisNet);
1519 return;
1520 } else {
1521 // tear down the other
1522 NetworkStateTracker otherNet =
1523 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001524 if (DBG) {
1525 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001526 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001527 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001528 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001529 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07001530 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001531 return;
1532 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001533 }
1534 }
1535 synchronized (ConnectivityService.this) {
1536 // have a new default network, release the transition wakelock in a second
1537 // if it's held. The second pause is to allow apps to reconnect over the
1538 // new network
1539 if (mNetTransitionWakeLock.isHeld()) {
1540 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001541 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001542 mNetTransitionWakeLockSerialNumber, 0),
1543 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001544 }
1545 }
1546 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001547 // this will cause us to come up initially as unconnected and switching
1548 // to connected after our normal pause unless somebody reports us as reall
1549 // disconnected
1550 mDefaultInetConditionPublished = 0;
1551 mDefaultConnectionSequence++;
1552 mInetConditionChangeInFlight = false;
1553 // Don't do this - if we never sign in stay, grey
1554 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001557 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001558 handleConnectivityChange(type, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001559 sendConnectedBroadcast(info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
1561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001563 * After a change in the connectivity state of a network. We're mainly
1564 * concerned with making sure that the list of DNS servers is set up
1565 * according to which networks are connected, and ensuring that the
1566 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001568 private void handleConnectivityChange(int netType, boolean doReset) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001570 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001571 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001573 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001574
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001575 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001576 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07001577 handleApplyDefaultProxy(netType);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001578 addDefaultRoute(mNetTrackers[netType]);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001579 } else {
Robert Greenwalt13ec4062011-04-01 10:51:22 -07001580 // many radios add a default route even when we don't want one.
1581 // remove the default route unless we need it for our active network
1582 if (mActiveDefaultNetwork != -1) {
1583 LinkProperties defaultLinkProperties =
1584 mNetTrackers[mActiveDefaultNetwork].getLinkProperties();
1585 LinkProperties newLinkProperties =
1586 mNetTrackers[netType].getLinkProperties();
1587 String defaultIface = defaultLinkProperties.getInterfaceName();
1588 if (defaultIface != null &&
1589 !defaultIface.equals(newLinkProperties.getInterfaceName())) {
1590 removeDefaultRoute(mNetTrackers[netType]);
1591 }
1592 }
Michael Jurka8fad7ee2011-03-30 19:54:08 -07001593 addPrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001594 }
1595 } else {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001596 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001597 removeDefaultRoute(mNetTrackers[netType]);
1598 } else {
1599 removePrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07001602
1603 if (doReset) {
1604 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1605 if (linkProperties != null) {
1606 String iface = linkProperties.getInterfaceName();
1607 if (TextUtils.isEmpty(iface) == false) {
1608 if (DBG) log("resetConnections(" + iface + ")");
1609 NetworkUtils.resetConnections(iface);
1610 }
1611 }
1612 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001613
1614 // TODO: Temporary notifying upstread change to Tethering.
1615 // @see bug/4455071
1616 /** Notify TetheringService if interface name has been changed. */
1617 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1618 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1619 if (isTetheringSupported()) {
1620 mTethering.handleTetherIfaceChange();
1621 }
1622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 }
1624
Irfan Sheriffd649c122010-06-09 15:39:36 -07001625 private void addPrivateDnsRoutes(NetworkStateTracker nt) {
Irfan Sheriffd649c122010-06-09 15:39:36 -07001626 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001627 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001628 if (p == null) return;
1629 String interfaceName = p.getInterfaceName();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001630
1631 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001632 log("addPrivateDnsRoutes for " + nt +
Irfan Sheriffd649c122010-06-09 15:39:36 -07001633 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1634 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001635 if (interfaceName != null && !privateDnsRouteSet) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001636 Collection<InetAddress> dnsList = p.getDnses();
1637 for (InetAddress dns : dnsList) {
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001638 addHostRoute(nt, dns, 0);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001639 }
1640 nt.privateDnsRouteSet(true);
1641 }
1642 }
1643
1644 private void removePrivateDnsRoutes(NetworkStateTracker nt) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001645 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001646 if (p == null) return;
1647 String interfaceName = p.getInterfaceName();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001648 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1649 if (interfaceName != null && privateDnsRouteSet) {
1650 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001651 log("removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
Irfan Sheriffd649c122010-06-09 15:39:36 -07001652 " (" + interfaceName + ")");
1653 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001654
1655 Collection<InetAddress> dnsList = p.getDnses();
1656 for (InetAddress dns : dnsList) {
1657 if (DBG) log(" removing " + dns);
1658 RouteInfo route = RouteInfo.makeHostRoute(dns);
1659 try {
1660 mNetd.removeRoute(interfaceName, route);
1661 } catch (Exception ex) {
1662 loge("error (" + ex + ") removing dns route " + route);
1663 }
1664 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001665 nt.privateDnsRouteSet(false);
1666 }
1667 }
1668
Irfan Sheriffd649c122010-06-09 15:39:36 -07001669
1670 private void addDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001671 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001672 if (p == null) return;
1673 String interfaceName = p.getInterfaceName();
Robert Greenwalt992564e2011-02-09 13:56:06 -08001674 if (TextUtils.isEmpty(interfaceName)) return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001675
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001676 for (RouteInfo route : p.getRoutes()) {
Robert Greenwaltaa70f102011-04-28 14:28:50 -07001677 //TODO - handle non-default routes
1678 if (route.isDefaultRoute()) {
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001679 if (DBG) log("adding default route " + route);
Robert Greenwaltaa70f102011-04-28 14:28:50 -07001680 InetAddress gateway = route.getGateway();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001681 if (addHostRoute(nt, gateway, 0)) {
1682 try {
1683 mNetd.addRoute(interfaceName, route);
1684 } catch (Exception e) {
1685 loge("error adding default route " + route);
1686 continue;
1687 }
Robert Greenwaltaa70f102011-04-28 14:28:50 -07001688 if (DBG) {
1689 NetworkInfo networkInfo = nt.getNetworkInfo();
1690 log("addDefaultRoute for " + networkInfo.getTypeName() +
1691 " (" + interfaceName + "), GatewayAddr=" +
1692 gateway.getHostAddress());
1693 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001694 } else {
1695 loge("error adding host route for default route " + route);
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07001696 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001697 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001698 }
1699 }
1700
1701
1702 public void removeDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001703 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001704 if (p == null) return;
1705 String interfaceName = p.getInterfaceName();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001706
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001707 if (interfaceName == null) return;
1708
1709 for (RouteInfo route : p.getRoutes()) {
1710 //TODO - handle non-default routes
1711 if (route.isDefaultRoute()) {
1712 try {
1713 mNetd.removeRoute(interfaceName, route);
1714 } catch (Exception ex) {
1715 loge("error (" + ex + ") removing default route " + route);
1716 continue;
1717 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07001718 if (DBG) {
1719 NetworkInfo networkInfo = nt.getNetworkInfo();
1720 log("removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1721 interfaceName + ")");
1722 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001723 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001724 }
1725 }
1726
1727 /**
1728 * Reads the network specific TCP buffer sizes from SystemProperties
1729 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1730 * wide use
1731 */
1732 public void updateNetworkSettings(NetworkStateTracker nt) {
1733 String key = nt.getTcpBufferSizesPropName();
1734 String bufferSizes = SystemProperties.get(key);
1735
1736 if (bufferSizes.length() == 0) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001737 loge(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07001738
1739 // Setting to default values so we won't be stuck to previous values
1740 key = "net.tcp.buffersize.default";
1741 bufferSizes = SystemProperties.get(key);
1742 }
1743
1744 // Set values in kernel
1745 if (bufferSizes.length() != 0) {
1746 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001747 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07001748 + "] which comes from [" + key + "]");
1749 }
1750 setBufferSize(bufferSizes);
1751 }
1752 }
1753
1754 /**
1755 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1756 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1757 *
1758 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1759 * writeMin, writeInitial, writeMax"
1760 */
1761 private void setBufferSize(String bufferSizes) {
1762 try {
1763 String[] values = bufferSizes.split(",");
1764
1765 if (values.length == 6) {
1766 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04001767 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1768 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1769 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1770 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1771 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1772 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001773 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001774 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001775 }
1776 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001777 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001778 }
1779 }
1780
Robert Greenwalt42acef32009-08-12 16:08:25 -07001781 /**
1782 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1783 * on the highest priority active net which this process requested.
1784 * If there aren't any, clear it out
1785 */
1786 private void reassessPidDns(int myPid, boolean doBump)
1787 {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001788 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001789 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001790 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001791 continue;
1792 }
1793 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001794 if (nt.getNetworkInfo().isConnected() &&
1795 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001796 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001797 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001798 List pids = mNetRequestersPids[i];
1799 for (int j=0; j<pids.size(); j++) {
1800 Integer pid = (Integer)pids.get(j);
1801 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001802 Collection<InetAddress> dnses = p.getDnses();
1803 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001804 if (doBump) {
1805 bumpDns();
1806 }
1807 return;
1808 }
1809 }
1810 }
1811 }
1812 // nothing found - delete
1813 for (int i = 1; ; i++) {
1814 String prop = "net.dns" + i + "." + myPid;
1815 if (SystemProperties.get(prop).length() == 0) {
1816 if (doBump) {
1817 bumpDns();
1818 }
1819 return;
1820 }
1821 SystemProperties.set(prop, "");
1822 }
1823 }
1824
Robert Greenwalt10398722010-12-17 15:20:36 -08001825 // return true if results in a change
1826 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001827 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08001828 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001829 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001830 String dnsString = dns.getHostAddress();
1831 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1832 changed = true;
1833 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1834 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001835 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001836 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001837 }
1838
1839 private void bumpDns() {
1840 /*
1841 * Bump the property that tells the name resolver library to reread
1842 * the DNS server list from the properties.
1843 */
1844 String propVal = SystemProperties.get("net.dnschange");
1845 int n = 0;
1846 if (propVal.length() != 0) {
1847 try {
1848 n = Integer.parseInt(propVal);
1849 } catch (NumberFormatException e) {}
1850 }
1851 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07001852 /*
1853 * Tell the VMs to toss their DNS caches
1854 */
1855 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1856 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001857 /*
1858 * Connectivity events can happen before boot has completed ...
1859 */
1860 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07001861 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001862 }
1863
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001864 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001865 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001866 NetworkStateTracker nt = mNetTrackers[netType];
1867 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001868 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001869 if (p == null) return;
1870 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08001871 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001872 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001873 int j = 1;
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001874 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001875 String dnsString = mDefaultDns.getHostAddress();
1876 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1877 if (DBG) {
1878 log("no dns provided - using " + dnsString);
1879 }
1880 changed = true;
1881 SystemProperties.set("net.dns1", dnsString);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001882 }
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001883 j++;
1884 } else {
1885 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001886 String dnsString = dns.getHostAddress();
1887 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1888 j++;
1889 continue;
1890 }
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001891 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001892 log("adding dns " + dns + " for " +
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001893 nt.getNetworkInfo().getTypeName());
1894 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001895 changed = true;
1896 SystemProperties.set("net.dns" + j++, dnsString);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07001897 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001898 }
1899 for (int k=j ; k<mNumDnsEntries; k++) {
Robert Greenwalt10398722010-12-17 15:20:36 -08001900 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1901 if (DBG) log("erasing net.dns" + k);
1902 changed = true;
1903 SystemProperties.set("net.dns" + k, "");
1904 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001905 }
1906 mNumDnsEntries = j;
1907 } else {
1908 // set per-pid dns for attached secondary nets
1909 List pids = mNetRequestersPids[netType];
1910 for (int y=0; y< pids.size(); y++) {
1911 Integer pid = (Integer)pids.get(y);
Robert Greenwalt10398722010-12-17 15:20:36 -08001912 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 }
1914 }
Robert Greenwalt10398722010-12-17 15:20:36 -08001915 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001917 }
1918
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001919 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001920 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1921 NETWORK_RESTORE_DELAY_PROP_NAME);
1922 if(restoreDefaultNetworkDelayStr != null &&
1923 restoreDefaultNetworkDelayStr.length() != 0) {
1924 try {
1925 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1926 } catch (NumberFormatException e) {
1927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001929 // if the system property isn't set, use the value for the apn type
1930 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1931
1932 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1933 (mNetConfigs[networkType] != null)) {
1934 ret = mNetConfigs[networkType].restoreTime;
1935 }
1936 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 }
1938
1939 @Override
1940 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001941 if (mContext.checkCallingOrSelfPermission(
1942 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001944 pw.println("Permission Denial: can't dump ConnectivityService " +
1945 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1946 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 return;
1948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 pw.println();
1950 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08001951 if (nst != null) {
1952 if (nst.getNetworkInfo().isConnected()) {
1953 pw.println("Active network: " + nst.getNetworkInfo().
1954 getTypeName());
1955 }
1956 pw.println(nst.getNetworkInfo());
1957 pw.println(nst);
1958 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001961
1962 pw.println("Network Requester Pids:");
1963 for (int net : mPriorityList) {
1964 String pidString = net + ": ";
1965 for (Object pid : mNetRequestersPids[net]) {
1966 pidString = pidString + pid.toString() + ", ";
1967 }
1968 pw.println(pidString);
1969 }
1970 pw.println();
1971
1972 pw.println("FeatureUsers:");
1973 for (Object requester : mFeatureUsers) {
1974 pw.println(requester.toString());
1975 }
1976 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001977
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001978 synchronized (this) {
1979 pw.println("NetworkTranstionWakeLock is currently " +
1980 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1981 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1982 }
1983 pw.println();
1984
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001985 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001986
1987 if (mInetLog != null) {
1988 pw.println();
1989 pw.println("Inet condition reports:");
1990 for(int i = 0; i < mInetLog.size(); i++) {
1991 pw.println(mInetLog.get(i));
1992 }
1993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 }
1995
Robert Greenwalt42acef32009-08-12 16:08:25 -07001996 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07001998 public MyHandler(Looper looper) {
1999 super(looper);
2000 }
2001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 @Override
2003 public void handleMessage(Message msg) {
2004 NetworkInfo info;
2005 switch (msg.what) {
2006 case NetworkStateTracker.EVENT_STATE_CHANGED:
2007 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002008 int type = info.getType();
2009 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002010
Wink Savilleed9c02b2010-12-03 12:01:38 -08002011 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002012 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002013 state + "/" + info.getDetailedState());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014
2015 // Connectivity state changed:
2016 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002017 // [12-9] Network subtype (for mobile network, as defined
2018 // by TelephonyManager)
2019 // [8-3] Detailed state ordinal (as defined by
2020 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 // [2-0] Network type (as defined by ConnectivityManager)
2022 int eventLogParam = (info.getType() & 0x7) |
2023 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2024 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002025 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002026 eventLogParam);
2027
2028 if (info.getDetailedState() ==
2029 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002031 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002033 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002035 // the logic here is, handle SUSPENDED the same as
2036 // DISCONNECTED. The only difference being we are
2037 // broadcasting an intent with NetworkInfo that's
2038 // suspended. This allows the applications an
2039 // opportunity to handle DISCONNECTED and SUSPENDED
2040 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002042 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 handleConnect(info);
2044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002047 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002048 // TODO: Temporary allowing network configuration
2049 // change not resetting sockets.
2050 // @see bug/4455071
2051 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002053 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002054 String causedBy = null;
2055 synchronized (ConnectivityService.this) {
2056 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2057 mNetTransitionWakeLock.isHeld()) {
2058 mNetTransitionWakeLock.release();
2059 causedBy = mNetTransitionWakeLockCausedBy;
2060 }
2061 }
2062 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002063 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002064 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002065 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002066 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002067 FeatureUser u = (FeatureUser)msg.obj;
2068 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002069 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002070 case EVENT_INET_CONDITION_CHANGE:
2071 {
2072 int netType = msg.arg1;
2073 int condition = msg.arg2;
2074 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002075 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002076 }
2077 case EVENT_INET_CONDITION_HOLD_END:
2078 {
2079 int netType = msg.arg1;
2080 int sequence = msg.arg2;
2081 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002082 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002083 }
2084 case EVENT_SET_NETWORK_PREFERENCE:
2085 {
2086 int preference = msg.arg1;
2087 handleSetNetworkPreference(preference);
2088 break;
2089 }
2090 case EVENT_SET_BACKGROUND_DATA:
2091 {
2092 boolean enabled = (msg.arg1 == ENABLED);
2093 handleSetBackgroundData(enabled);
2094 break;
2095 }
2096 case EVENT_SET_MOBILE_DATA:
2097 {
2098 boolean enabled = (msg.arg1 == ENABLED);
2099 handleSetMobileData(enabled);
2100 break;
2101 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002102 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2103 {
2104 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002105 break;
2106 }
2107 case EVENT_SET_DEPENDENCY_MET:
2108 {
2109 boolean met = (msg.arg1 == ENABLED);
2110 handleSetDependencyMet(msg.arg2, met);
2111 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 }
2114 }
2115 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002116
2117 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002118 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002119 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002120
2121 if (isTetheringSupported()) {
2122 return mTethering.tether(iface);
2123 } else {
2124 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2125 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002126 }
2127
2128 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002129 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002130 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002131
2132 if (isTetheringSupported()) {
2133 return mTethering.untether(iface);
2134 } else {
2135 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2136 }
2137 }
2138
2139 // javadoc from interface
2140 public int getLastTetherError(String iface) {
2141 enforceTetherAccessPermission();
2142
2143 if (isTetheringSupported()) {
2144 return mTethering.getLastTetherError(iface);
2145 } else {
2146 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2147 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002148 }
2149
2150 // TODO - proper iface API for selection by property, inspection, etc
2151 public String[] getTetherableUsbRegexs() {
2152 enforceTetherAccessPermission();
2153 if (isTetheringSupported()) {
2154 return mTethering.getTetherableUsbRegexs();
2155 } else {
2156 return new String[0];
2157 }
2158 }
2159
2160 public String[] getTetherableWifiRegexs() {
2161 enforceTetherAccessPermission();
2162 if (isTetheringSupported()) {
2163 return mTethering.getTetherableWifiRegexs();
2164 } else {
2165 return new String[0];
2166 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002167 }
2168
Danica Chang6fdd0c62010-08-11 14:54:43 -07002169 public String[] getTetherableBluetoothRegexs() {
2170 enforceTetherAccessPermission();
2171 if (isTetheringSupported()) {
2172 return mTethering.getTetherableBluetoothRegexs();
2173 } else {
2174 return new String[0];
2175 }
2176 }
2177
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002178 // TODO - move iface listing, queries, etc to new module
2179 // javadoc from interface
2180 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002181 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002182 return mTethering.getTetherableIfaces();
2183 }
2184
2185 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002186 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002187 return mTethering.getTetheredIfaces();
2188 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002189
Robert Greenwalt5a735062010-03-02 17:25:02 -08002190 public String[] getTetheringErroredIfaces() {
2191 enforceTetherAccessPermission();
2192 return mTethering.getErroredIfaces();
2193 }
2194
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002195 // if ro.tether.denied = true we default to no tethering
2196 // gservices could set the secure setting to 1 though to enable it on a build where it
2197 // had previously been turned off.
2198 public boolean isTetheringSupported() {
2199 enforceTetherAccessPermission();
2200 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002201 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2202 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2203 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002204 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002205
2206 // An API NetworkStateTrackers can call when they lose their network.
2207 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2208 // whichever happens first. The timer is started by the first caller and not
2209 // restarted by subsequent callers.
2210 public void requestNetworkTransitionWakelock(String forWhom) {
2211 enforceConnectivityInternalPermission();
2212 synchronized (this) {
2213 if (mNetTransitionWakeLock.isHeld()) return;
2214 mNetTransitionWakeLockSerialNumber++;
2215 mNetTransitionWakeLock.acquire();
2216 mNetTransitionWakeLockCausedBy = forWhom;
2217 }
2218 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002219 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002220 mNetTransitionWakeLockSerialNumber, 0),
2221 mNetTransitionWakeLockTimeout);
2222 return;
2223 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002224
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002225 // 100 percent is full good, 0 is full bad.
2226 public void reportInetCondition(int networkType, int percentage) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002227 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002228 mContext.enforceCallingOrSelfPermission(
2229 android.Manifest.permission.STATUS_BAR,
2230 "ConnectivityService");
2231
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002232 if (DBG) {
2233 int pid = getCallingPid();
2234 int uid = getCallingUid();
2235 String s = pid + "(" + uid + ") reports inet is " +
2236 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2237 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2238 mInetLog.add(s);
2239 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2240 mInetLog.remove(0);
2241 }
2242 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002243 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002244 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2245 }
2246
2247 private void handleInetConditionChange(int netType, int condition) {
2248 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002249 log("Inet connectivity change, net=" +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002250 netType + ", condition=" + condition +
2251 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2252 }
2253 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002254 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002255 return;
2256 }
2257 if (mActiveDefaultNetwork != netType) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002258 if (DBG) log("given net not default - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002259 return;
2260 }
2261 mDefaultInetCondition = condition;
2262 int delay;
2263 if (mInetConditionChangeInFlight == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002264 if (DBG) log("starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002265 // setup a new hold to debounce this
2266 if (mDefaultInetCondition > 50) {
2267 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2268 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2269 } else {
2270 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2271 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2272 }
2273 mInetConditionChangeInFlight = true;
2274 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2275 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2276 } else {
2277 // we've set the new condition, when this hold ends that will get
2278 // picked up
Wink Savilleed9c02b2010-12-03 12:01:38 -08002279 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002280 }
2281 }
2282
2283 private void handleInetConditionHoldEnd(int netType, int sequence) {
2284 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002285 log("Inet hold end, net=" + netType +
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002286 ", condition =" + mDefaultInetCondition +
2287 ", published condition =" + mDefaultInetConditionPublished);
2288 }
2289 mInetConditionChangeInFlight = false;
2290
2291 if (mActiveDefaultNetwork == -1) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002292 if (DBG) log("no active default network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002293 return;
2294 }
2295 if (mDefaultConnectionSequence != sequence) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002296 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002297 return;
2298 }
2299 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002300 if (DBG) log("no change in condition - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002301 return;
2302 }
2303 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2304 if (networkInfo.isConnected() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002305 if (DBG) log("default network not connected - aborting");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002306 return;
2307 }
2308 mDefaultInetConditionPublished = mDefaultInetCondition;
2309 sendInetConditionBroadcast(networkInfo);
2310 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002311 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002312
2313 public synchronized ProxyProperties getProxy() {
2314 if (mGlobalProxy != null) return mGlobalProxy;
2315 if (mDefaultProxy != null) return mDefaultProxy;
2316 return null;
2317 }
2318
2319 public void setGlobalProxy(ProxyProperties proxyProperties) {
2320 enforceChangePermission();
2321 synchronized (mGlobalProxyLock) {
2322 if (proxyProperties == mGlobalProxy) return;
2323 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2324 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2325
2326 String host = "";
2327 int port = 0;
2328 String exclList = "";
2329 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2330 mGlobalProxy = new ProxyProperties(proxyProperties);
2331 host = mGlobalProxy.getHost();
2332 port = mGlobalProxy.getPort();
2333 exclList = mGlobalProxy.getExclusionList();
2334 } else {
2335 mGlobalProxy = null;
2336 }
2337 ContentResolver res = mContext.getContentResolver();
2338 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2339 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002340 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002341 exclList);
2342 }
2343
2344 if (mGlobalProxy == null) {
2345 proxyProperties = mDefaultProxy;
2346 }
2347 sendProxyBroadcast(proxyProperties);
2348 }
2349
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002350 private void loadGlobalProxy() {
2351 ContentResolver res = mContext.getContentResolver();
2352 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2353 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2354 String exclList = Settings.Secure.getString(res,
2355 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2356 if (!TextUtils.isEmpty(host)) {
2357 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2358 synchronized (mGlobalProxyLock) {
2359 mGlobalProxy = proxyProperties;
2360 }
2361 }
2362 }
2363
Robert Greenwalt434203a2010-10-11 16:00:27 -07002364 public ProxyProperties getGlobalProxy() {
2365 synchronized (mGlobalProxyLock) {
2366 return mGlobalProxy;
2367 }
2368 }
2369
2370 private void handleApplyDefaultProxy(int type) {
2371 // check if new default - push it out to all VM if so
2372 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2373 synchronized (this) {
2374 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2375 if (mDefaultProxy == proxy) return;
2376 if (!TextUtils.isEmpty(proxy.getHost())) {
2377 mDefaultProxy = proxy;
2378 } else {
2379 mDefaultProxy = null;
2380 }
2381 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002382 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002383 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2384 if (mGlobalProxy != null) return;
2385 sendProxyBroadcast(proxy);
2386 }
2387
2388 private void handleDeprecatedGlobalHttpProxy() {
2389 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2390 Settings.Secure.HTTP_PROXY);
2391 if (!TextUtils.isEmpty(proxy)) {
2392 String data[] = proxy.split(":");
2393 String proxyHost = data[0];
2394 int proxyPort = 8080;
2395 if (data.length > 1) {
2396 try {
2397 proxyPort = Integer.parseInt(data[1]);
2398 } catch (NumberFormatException e) {
2399 return;
2400 }
2401 }
2402 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2403 setGlobalProxy(p);
2404 }
2405 }
2406
2407 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002408 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002409 log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002410 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002411 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2412 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002413 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002414 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002415 }
2416
2417 private static class SettingsObserver extends ContentObserver {
2418 private int mWhat;
2419 private Handler mHandler;
2420 SettingsObserver(Handler handler, int what) {
2421 super(handler);
2422 mHandler = handler;
2423 mWhat = what;
2424 }
2425
2426 void observe(Context context) {
2427 ContentResolver resolver = context.getContentResolver();
2428 resolver.registerContentObserver(Settings.Secure.getUriFor(
2429 Settings.Secure.HTTP_PROXY), false, this);
2430 }
2431
2432 @Override
2433 public void onChange(boolean selfChange) {
2434 mHandler.obtainMessage(mWhat).sendToTarget();
2435 }
2436 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002437
2438 private void log(String s) {
2439 Slog.d(TAG, s);
2440 }
2441
2442 private void loge(String s) {
2443 Slog.e(TAG, s);
2444 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002445
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002446 int convertFeatureToNetworkType(String feature){
2447 int networkType = -1;
2448 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2449 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2450 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2451 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2452 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2453 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2454 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2455 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2456 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2457 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2458 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2459 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2460 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2461 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2462 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2463 }
2464 return networkType;
2465 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002466
2467 private static <T> T checkNotNull(T value, String message) {
2468 if (value == null) {
2469 throw new NullPointerException(message);
2470 }
2471 return value;
2472 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002473
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002474 /**
2475 * Protect a socket from VPN routing rules. This method is used by
2476 * VpnBuilder and not available in ConnectivityManager. Permission
2477 * checks are done in Vpn class.
2478 * @hide
2479 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002480 @Override
2481 public void protectVpn(ParcelFileDescriptor socket) {
2482 mVpn.protect(socket, getDefaultInterface());
2483 }
2484
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002485 /**
2486 * Prepare for a VPN application. This method is used by VpnDialogs
2487 * and not available in ConnectivityManager. Permission checks are
2488 * done in Vpn class.
2489 * @hide
2490 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002491 @Override
2492 public String prepareVpn(String packageName) {
2493 return mVpn.prepare(packageName);
2494 }
2495
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002496 /**
2497 * Configure a TUN interface and return its file descriptor. Parameters
2498 * are encoded and opaque to this class. This method is used by VpnBuilder
2499 * and not available in ConnectivityManager. Permission checks are done
2500 * in Vpn class.
2501 * @hide
2502 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002503 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002504 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002505 return mVpn.establish(config);
2506 }
2507
2508 private String getDefaultInterface() {
2509 if (ConnectivityManager.isNetworkTypeValid(mActiveDefaultNetwork)) {
2510 NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
2511 if (tracker != null) {
2512 LinkProperties properties = tracker.getLinkProperties();
2513 if (properties != null) {
2514 return properties.getInterfaceName();
2515 }
2516 }
2517 }
2518 throw new IllegalStateException("No default interface");
2519 }
2520
2521 /**
2522 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2523 * through NetworkStateTracker since it works differently. For example, it
2524 * needs to override DNS servers but never takes the default routes. It
2525 * relies on another data network, and it could keep existing connections
2526 * alive after reconnecting, switching between networks, or even resuming
2527 * from deep sleep. Calls from applications should be done synchronously
2528 * to avoid race conditions. As these are all hidden APIs, refactoring can
2529 * be done whenever a better abstraction is developed.
2530 */
2531 public class VpnCallback {
2532
2533 private VpnCallback() {
2534 }
2535
Chia-chi Yeh8909b102011-07-01 01:09:42 -07002536 public synchronized void override(List<String> dnsServers, List<String> searchDomains) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002537 // TODO: override DNS servers and http proxy.
2538 }
2539
2540 public synchronized void restore() {
2541 // TODO: restore VPN changes.
2542 }
2543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544}