blob: f3b50601e75d67807757faa00a4367122ba0d080 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070020import static android.net.ConnectivityManager.isNetworkTypeValid;
21import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070022import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070023
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080024import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080025import android.content.ContentResolver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070029import android.database.ContentObserver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080030import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080031import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080032import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080033import android.net.IConnectivityManager;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070034import android.net.INetworkPolicyListener;
35import android.net.INetworkPolicyManager;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080036import android.net.LinkProperties;
The Android Open Source Project28527d22009-03-03 19:31:44 -080037import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070038import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080039import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070040import android.net.NetworkInfo.DetailedState;
Jeff Sharkey21062e72011-05-28 20:56:34 -070041import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080042import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070043import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070044import android.net.Proxy;
45import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070046import android.net.RouteInfo;
Hung-ying Tyan4e723422011-01-19 16:48:38 +080047import android.net.vpn.VpnManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -080048import android.net.wifi.WifiStateTracker;
49import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040050import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080051import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070052import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070053import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070054import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080055import android.os.Looper;
56import android.os.Message;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070057import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070058import android.os.PowerManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070059import android.os.RemoteException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080060import android.os.ServiceManager;
61import android.os.SystemProperties;
62import android.provider.Settings;
Robert Greenwalt2034b912009-08-12 16:08:25 -070063import android.text.TextUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080064import android.util.EventLog;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080065import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070066import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -080067
Chia-chi Yeh75cacd52011-06-15 17:07:27 -070068import com.android.internal.net.VpnConfig;
Robert Greenwalt2034b912009-08-12 16:08:25 -070069import com.android.internal.telephony.Phone;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080070import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070071import com.android.server.connectivity.Vpn;
72
Jeff Sharkey21062e72011-05-28 20:56:34 -070073import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070074import com.google.android.collect.Sets;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -080075
The Android Open Source Project28527d22009-03-03 19:31:44 -080076import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -070077import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -080078import java.io.PrintWriter;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070079import java.net.InetAddress;
80import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -070081import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070082import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -070083import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -070084import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070085import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -070086import java.util.List;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070087import java.util.concurrent.atomic.AtomicBoolean;
The Android Open Source Project28527d22009-03-03 19:31:44 -080088
89/**
90 * @hide
91 */
92public class ConnectivityService extends IConnectivityManager.Stub {
93
Robert Greenwalt063dc7d2010-10-05 19:12:26 -070094 private static final boolean DBG = true;
The Android Open Source Project28527d22009-03-03 19:31:44 -080095 private static final String TAG = "ConnectivityService";
96
Jeff Sharkey921ebf22011-05-19 17:12:49 -070097 private static final boolean LOGD_RULES = false;
98
Robert Greenwalt2034b912009-08-12 16:08:25 -070099 // how long to wait before switching back to a radio's default network
100 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
101 // system property that can override the above value
102 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
103 "android.telephony.apn-restore";
104
Robert Greenwaltbd492212011-05-06 17:10:53 -0700105 // used in recursive route setting to add gateways for the host for which
106 // a host route was requested.
107 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
108
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800109 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800110 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800111
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700112 private Vpn mVpn;
113
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700114 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
115 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700116 /** Currently active network rules by UID. */
117 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700118 /** Set of ifaces that are costly. */
119 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700120
The Android Open Source Project28527d22009-03-03 19:31:44 -0800121 /**
122 * Sometimes we want to refer to the individual network state
123 * trackers separately, and sometimes we just want to treat them
124 * abstractly.
125 */
126 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700127
128 /**
129 * A per Net list of the PID's that requested access to the net
130 * used both as a refcount and for per-PID DNS selection
131 */
132 private List mNetRequestersPids[];
133
Robert Greenwalt2034b912009-08-12 16:08:25 -0700134 // priority order of the nettrackers
135 // (excluding dynamically set mNetworkPreference)
136 // TODO - move mNetworkTypePreference into this
137 private int[] mPriorityList;
138
The Android Open Source Project28527d22009-03-03 19:31:44 -0800139 private Context mContext;
140 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700141 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700142 // 0 is full bad, 100 is full good
143 private int mDefaultInetCondition = 0;
144 private int mDefaultInetConditionPublished = 0;
145 private boolean mInetConditionChangeInFlight = false;
146 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800147
148 private int mNumDnsEntries;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800149
150 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700151 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800152
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800153 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
154
Robert Greenwalt355205c2011-05-10 15:05:02 -0700155 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700156 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700157
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700158 private static final int ENABLED = 1;
159 private static final int DISABLED = 0;
160
161 // Share the event space with NetworkStateTracker (which can't see this
162 // internal class but sends us events). If you change these, change
163 // NetworkStateTracker.java too.
164 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
165 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
166
167 /**
168 * used internally as a delayed event to make us switch back to the
169 * default network
170 */
171 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
172 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
173
174 /**
175 * used internally to change our mobile data enabled flag
176 */
177 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
178 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
179
180 /**
181 * used internally to change our network preference setting
182 * arg1 = networkType to prefer
183 */
184 private static final int EVENT_SET_NETWORK_PREFERENCE =
185 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
186
187 /**
188 * used internally to synchronize inet condition reports
189 * arg1 = networkType
190 * arg2 = condition (0 bad, 100 good)
191 */
192 private static final int EVENT_INET_CONDITION_CHANGE =
193 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
194
195 /**
196 * used internally to mark the end of inet condition hold periods
197 * arg1 = networkType
198 */
199 private static final int EVENT_INET_CONDITION_HOLD_END =
200 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
201
202 /**
203 * used internally to set the background data preference
204 * arg1 = TRUE for enabled, FALSE for disabled
205 */
206 private static final int EVENT_SET_BACKGROUND_DATA =
207 MAX_NETWORK_STATE_TRACKER_EVENT + 6;
208
209 /**
210 * used internally to set enable/disable cellular data
211 * arg1 = ENBALED or DISABLED
212 */
213 private static final int EVENT_SET_MOBILE_DATA =
214 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
215
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700216 /**
217 * used internally to clear a wakelock when transitioning
218 * from one net to another
219 */
220 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
221 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
222
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700223 /**
224 * used internally to reload global proxy settings
225 */
226 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
227 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
228
Robert Greenwalt34848c02011-03-25 13:09:25 -0700229 /**
230 * used internally to set external dependency met/unmet
231 * arg1 = ENABLED (met) or DISABLED (unmet)
232 * arg2 = NetworkType
233 */
234 private static final int EVENT_SET_DEPENDENCY_MET =
235 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
236
Robert Greenwalt2034b912009-08-12 16:08:25 -0700237 private Handler mHandler;
238
239 // list of DeathRecipients used to make sure features are turned off when
240 // a process dies
241 private List mFeatureUsers;
242
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400243 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800244 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400245
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700246 private PowerManager.WakeLock mNetTransitionWakeLock;
247 private String mNetTransitionWakeLockCausedBy = "";
248 private int mNetTransitionWakeLockSerialNumber;
249 private int mNetTransitionWakeLockTimeout;
250
Robert Greenwalt94daa182010-09-01 11:34:05 -0700251 private InetAddress mDefaultDns;
252
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700253 // used in DBG mode to track inet condition reports
254 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
255 private ArrayList mInetLog;
256
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700257 // track the current default http proxy - tell the world if we get a new one (real change)
258 private ProxyProperties mDefaultProxy = null;
259 // track the global proxy.
260 private ProxyProperties mGlobalProxy = null;
261 private final Object mGlobalProxyLock = new Object();
262
263 private SettingsObserver mSettingsObserver;
264
Robert Greenwalt34848c02011-03-25 13:09:25 -0700265 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700266 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700267
Robert Greenwalt12c44552009-12-07 11:33:18 -0800268 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700269 public int mSimultaneity;
270 public int mType;
271 public RadioAttributes(String init) {
272 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700273 mType = Integer.parseInt(fragments[0]);
274 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700275 }
276 }
277 RadioAttributes[] mRadioAttributes;
278
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700279 public ConnectivityService(
280 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800281 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800282
Wink Saville775aad62010-09-02 19:23:52 -0700283 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
284 handlerThread.start();
285 mHandler = new MyHandler(handlerThread.getLooper());
286
Robert Greenwaltd62c7002010-12-29 16:15:02 -0800287 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
288 Settings.Secure.BACKGROUND_DATA, 1) == 1);
289
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800290 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800291 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
292 String id = Settings.Secure.getString(context.getContentResolver(),
293 Settings.Secure.ANDROID_ID);
294 if (id != null && id.length() > 0) {
295 String name = new String("android_").concat(id);
296 SystemProperties.set("net.hostname", name);
297 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800298 }
299
Robert Greenwalt94daa182010-09-01 11:34:05 -0700300 // read our default dns server ip
301 String dns = Settings.Secure.getString(context.getContentResolver(),
302 Settings.Secure.DEFAULT_DNS_SERVER);
303 if (dns == null || dns.length() == 0) {
304 dns = context.getResources().getString(
305 com.android.internal.R.string.config_default_dns_server);
306 }
307 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800308 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
309 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800310 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700311 }
312
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700313 mContext = checkNotNull(context, "missing Context");
314 mNetd = checkNotNull(netd, "missing INetworkManagementService");
315 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700316
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700317 try {
318 mPolicyManager.registerListener(mPolicyListener);
319 } catch (RemoteException e) {
320 // ouch, no rules updates means some processes may never get network
321 Slog.e(TAG, "unable to register INetworkPolicyListener", e);
322 }
323
324 final PowerManager powerManager = (PowerManager) context.getSystemService(
325 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700326 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
327 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
328 com.android.internal.R.integer.config_networkTransitionTimeout);
329
Robert Greenwalt2034b912009-08-12 16:08:25 -0700330 mNetTrackers = new NetworkStateTracker[
331 ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700332
The Android Open Source Project28527d22009-03-03 19:31:44 -0800333 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt0659da32009-07-16 17:21:39 -0700334
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700335 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700336 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700337
Robert Greenwalt2034b912009-08-12 16:08:25 -0700338 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700339 String[] raStrings = context.getResources().getStringArray(
340 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700341 for (String raString : raStrings) {
342 RadioAttributes r = new RadioAttributes(raString);
343 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800344 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700345 continue;
346 }
347 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800348 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700349 r.mType);
350 continue;
351 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700352 mRadioAttributes[r.mType] = r;
353 }
354
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700355 String[] naStrings = context.getResources().getStringArray(
356 com.android.internal.R.array.networkAttributes);
357 for (String naString : naStrings) {
358 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700359 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700360 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800361 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700362 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700363 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700364 }
Wink Savillef2a62832011-04-07 14:23:45 -0700365 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800366 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700367 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700368 continue;
369 }
Wink Savillef2a62832011-04-07 14:23:45 -0700370 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800371 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700372 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700373 continue;
374 }
Wink Savillef2a62832011-04-07 14:23:45 -0700375 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700376 mNetworksDefined++;
377 } catch(Exception e) {
378 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700379 }
380 }
381
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700382 // high priority first
383 mPriorityList = new int[mNetworksDefined];
384 {
385 int insertionPoint = mNetworksDefined-1;
386 int currentLowest = 0;
387 int nextLowest = 0;
388 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700389 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700390 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700391 if (na.priority < currentLowest) continue;
392 if (na.priority > currentLowest) {
393 if (na.priority < nextLowest || nextLowest == 0) {
394 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700395 }
396 continue;
397 }
Wink Savillef2a62832011-04-07 14:23:45 -0700398 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700399 }
400 currentLowest = nextLowest;
401 nextLowest = 0;
402 }
403 }
404
405 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
406 for (int i : mPriorityList) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700407 mNetRequestersPids[i] = new ArrayList();
408 }
409
410 mFeatureUsers = new ArrayList();
411
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700412 mNumDnsEntries = 0;
413
414 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
415 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project28527d22009-03-03 19:31:44 -0800416 /*
417 * Create the network state trackers for Wi-Fi and mobile
418 * data. Maybe this could be done with a factory class,
419 * but it's not clear that it's worth it, given that
420 * the number of different network types is not going
421 * to change very often.
422 */
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700423 for (int netType : mPriorityList) {
Wink Savillef2a62832011-04-07 14:23:45 -0700424 switch (mNetConfigs[netType].radio) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700425 case ConnectivityManager.TYPE_WIFI:
Wink Savillee70c6f52010-12-03 12:01:38 -0800426 if (DBG) log("Starting Wifi Service.");
Wink Saville7fabfa22010-08-13 16:11:42 -0700427 WifiStateTracker wst = new WifiStateTracker();
Irfan Sheriff25be0762010-07-28 09:35:20 -0700428 WifiService wifiService = new WifiService(context);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700429 ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
Irfan Sheriff25be0762010-07-28 09:35:20 -0700430 wifiService.checkAndStartWifi();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700431 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
Wink Saville7fabfa22010-08-13 16:11:42 -0700432 wst.startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700433 break;
434 case ConnectivityManager.TYPE_MOBILE:
Wink Saville7fabfa22010-08-13 16:11:42 -0700435 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700436 mNetConfigs[netType].name);
Wink Saville7fabfa22010-08-13 16:11:42 -0700437 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700438 break;
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800439 case ConnectivityManager.TYPE_DUMMY:
440 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Savillef2a62832011-04-07 14:23:45 -0700441 mNetConfigs[netType].name);
Robert Greenwalteb123ac2010-12-06 13:56:24 -0800442 mNetTrackers[netType].startMonitoring(context, mHandler);
443 break;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800444 case ConnectivityManager.TYPE_BLUETOOTH:
445 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
446 mNetTrackers[netType].startMonitoring(context, mHandler);
447 break;
Benoit Goby211b5692010-12-22 14:29:40 -0800448 case ConnectivityManager.TYPE_ETHERNET:
449 mNetTrackers[netType] = EthernetDataTracker.getInstance();
450 mNetTrackers[netType].startMonitoring(context, mHandler);
451 break;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700452 default:
Wink Savillee70c6f52010-12-03 12:01:38 -0800453 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700454 mNetConfigs[netType].radio);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700455 continue;
456 }
457 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800458
Chia-chi Yeh4df51322011-05-11 16:35:13 -0700459 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
460 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
461
462 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700463 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700464 mTethering.getTetherableWifiRegexs().length != 0 ||
465 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700466 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800467
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700468 mVpn = new Vpn(mContext, new VpnCallback());
469
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700470 try {
471 nmService.registerObserver(mTethering);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700472 nmService.registerObserver(mVpn);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700473 } catch (RemoteException e) {
474 loge("Error registering observer :" + e);
475 }
476
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700477 if (DBG) {
478 mInetLog = new ArrayList();
479 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700480
481 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
482 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800483
484 loadGlobalProxy();
Hung-ying Tyan4e723422011-01-19 16:48:38 +0800485
486 VpnManager.startVpnService(context);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800487 }
488
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700489
The Android Open Source Project28527d22009-03-03 19:31:44 -0800490 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700491 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800492 * @param preference the new preference
493 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700494 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800495 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700496
497 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800498 }
499
500 public int getNetworkPreference() {
501 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700502 int preference;
503 synchronized(this) {
504 preference = mNetworkPreference;
505 }
506 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800507 }
508
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700509 private void handleSetNetworkPreference(int preference) {
510 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700511 mNetConfigs[preference] != null &&
512 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700513 if (mNetworkPreference != preference) {
514 final ContentResolver cr = mContext.getContentResolver();
515 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
516 synchronized(this) {
517 mNetworkPreference = preference;
518 }
519 enforcePreference();
520 }
521 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800522 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700523
The Android Open Source Project28527d22009-03-03 19:31:44 -0800524 private int getPersistedNetworkPreference() {
525 final ContentResolver cr = mContext.getContentResolver();
526
527 final int networkPrefSetting = Settings.Secure
528 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
529 if (networkPrefSetting != -1) {
530 return networkPrefSetting;
531 }
532
533 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
534 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700535
The Android Open Source Project28527d22009-03-03 19:31:44 -0800536 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700537 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800538 * In this method, we only tear down a non-preferred network. Establishing
539 * a connection to the preferred network is taken care of when we handle
540 * the disconnect event from the non-preferred network
541 * (see {@link #handleDisconnect(NetworkInfo)}).
542 */
543 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700544 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800545 return;
546
Robert Greenwalt2034b912009-08-12 16:08:25 -0700547 if (!mNetTrackers[mNetworkPreference].isAvailable())
548 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800549
Robert Greenwalt2034b912009-08-12 16:08:25 -0700550 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700551 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700552 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700553 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800554 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700555 " in enforcePreference");
556 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700557 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800558 }
559 }
560 }
561
562 private boolean teardown(NetworkStateTracker netTracker) {
563 if (netTracker.teardown()) {
564 netTracker.setTeardownRequested(true);
565 return true;
566 } else {
567 return false;
568 }
569 }
570
571 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700572 * Check if UID should be blocked from using the network represented by the
573 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700574 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700575 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
576 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700577
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700578 final boolean networkCostly;
579 final int uidRules;
580 synchronized (mRulesLock) {
581 networkCostly = mMeteredIfaces.contains(iface);
582 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700583 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700584
585 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
586 return true;
587 }
588
589 // no restrictive rules; network is visible
590 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700591 }
592
593 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700594 * Return a filtered {@link NetworkInfo}, potentially marked
595 * {@link DetailedState#BLOCKED} based on
596 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700597 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700598 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
599 NetworkInfo info = tracker.getNetworkInfo();
600 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700601 // network is blocked; clone and override state
602 info = new NetworkInfo(info);
603 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700604 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700605 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700606 }
607
608 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800609 * Return NetworkInfo for the active (i.e., connected) network interface.
610 * It is assumed that at most one network is active at a time. If more
611 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700612 * @return the info for the active network, or {@code null} if none is
613 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800614 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700615 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800616 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700617 enforceAccessPermission();
618 final int uid = Binder.getCallingUid();
619 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800620 }
621
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700622 @Override
623 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
624 enforceConnectivityInternalPermission();
625 return getNetworkInfo(mActiveDefaultNetwork, uid);
626 }
627
628 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800629 public NetworkInfo getNetworkInfo(int networkType) {
630 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700631 final int uid = Binder.getCallingUid();
632 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800633 }
634
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700635 private NetworkInfo getNetworkInfo(int networkType, int uid) {
636 NetworkInfo info = null;
637 if (isNetworkTypeValid(networkType)) {
638 final NetworkStateTracker tracker = mNetTrackers[networkType];
639 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700640 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700641 }
642 }
643 return info;
644 }
645
646 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800647 public NetworkInfo[] getAllNetworkInfo() {
648 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700649 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700650 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700651 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700652 for (NetworkStateTracker tracker : mNetTrackers) {
653 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700654 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700655 }
656 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800657 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700658 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800659 }
660
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700661 /**
662 * Return LinkProperties for the active (i.e., connected) default
663 * network interface. It is assumed that at most one default network
664 * is active at a time. If more than one is active, it is indeterminate
665 * which will be returned.
666 * @return the ip properties for the active network, or {@code null} if
667 * none is active
668 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700669 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700670 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700671 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700672 }
673
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700674 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700675 public LinkProperties getLinkProperties(int networkType) {
676 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700677 if (isNetworkTypeValid(networkType)) {
678 final NetworkStateTracker tracker = mNetTrackers[networkType];
679 if (tracker != null) {
680 return tracker.getLinkProperties();
681 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700682 }
683 return null;
684 }
685
Jeff Sharkey21062e72011-05-28 20:56:34 -0700686 @Override
687 public NetworkState[] getAllNetworkState() {
688 enforceAccessPermission();
689 final int uid = Binder.getCallingUid();
690 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700691 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700692 for (NetworkStateTracker tracker : mNetTrackers) {
693 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700694 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700695 result.add(new NetworkState(
696 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
697 }
698 }
699 }
700 return result.toArray(new NetworkState[result.size()]);
701 }
702
The Android Open Source Project28527d22009-03-03 19:31:44 -0800703 public boolean setRadios(boolean turnOn) {
704 boolean result = true;
705 enforceChangePermission();
706 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700707 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800708 }
709 return result;
710 }
711
712 public boolean setRadio(int netType, boolean turnOn) {
713 enforceChangePermission();
714 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
715 return false;
716 }
717 NetworkStateTracker tracker = mNetTrackers[netType];
718 return tracker != null && tracker.setRadio(turnOn);
719 }
720
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700721 /**
722 * Used to notice when the calling process dies so we can self-expire
723 *
724 * Also used to know if the process has cleaned up after itself when
725 * our auto-expire timer goes off. The timer has a link to an object.
726 *
727 */
Robert Greenwalt2034b912009-08-12 16:08:25 -0700728 private class FeatureUser implements IBinder.DeathRecipient {
729 int mNetworkType;
730 String mFeature;
731 IBinder mBinder;
732 int mPid;
733 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800734 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700735
736 FeatureUser(int type, String feature, IBinder binder) {
737 super();
738 mNetworkType = type;
739 mFeature = feature;
740 mBinder = binder;
741 mPid = getCallingPid();
742 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800743 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700744
Robert Greenwalt2034b912009-08-12 16:08:25 -0700745 try {
746 mBinder.linkToDeath(this, 0);
747 } catch (RemoteException e) {
748 binderDied();
749 }
750 }
751
752 void unlinkDeathRecipient() {
753 mBinder.unlinkToDeath(this, 0);
754 }
755
756 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800757 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800758 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
759 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700760 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700761 }
762
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700763 public void expire() {
Wink Savillee70c6f52010-12-03 12:01:38 -0800764 log("ConnectivityService FeatureUser expire(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800765 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
766 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700767 stopUsingNetworkFeature(this, false);
768 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -0800769
770 public String toString() {
771 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
772 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
773 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700774 }
775
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700776 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -0700777 public int startUsingNetworkFeature(int networkType, String feature,
778 IBinder binder) {
779 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800780 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700781 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800782 enforceChangePermission();
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700783 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwalt34848c02011-03-25 13:09:25 -0700784 mNetConfigs[networkType] == null) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700785 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800786 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700787
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700788 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700789
790 // TODO - move this into the MobileDataStateTracker
791 int usedNetworkType = networkType;
792 if(networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800793 usedNetworkType = convertFeatureToNetworkType(feature);
794 if (usedNetworkType < 0) {
795 Slog.e(TAG, "Can't match any netTracker!");
796 usedNetworkType = networkType;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700797 }
798 }
799 NetworkStateTracker network = mNetTrackers[usedNetworkType];
800 if (network != null) {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800801 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt2034b912009-08-12 16:08:25 -0700802 if (usedNetworkType != networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700803 NetworkStateTracker radio = mNetTrackers[networkType];
804 NetworkInfo ni = network.getNetworkInfo();
805
806 if (ni.isAvailable() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800807 if (DBG) log("special network not available");
Robert Greenwalt2cc87442010-12-29 14:35:21 -0800808 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
809 return Phone.APN_TYPE_NOT_AVAILABLE;
810 } else {
811 // else make the attempt anyway - probably giving REQUEST_STARTED below
812 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700813 }
814
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700815 synchronized(this) {
816 mFeatureUsers.add(f);
817 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
818 // this gets used for per-pid dns when connected
819 mNetRequestersPids[usedNetworkType].add(currentPid);
820 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700821 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700822
Robert Greenwalt20f819c2011-05-03 19:02:44 -0700823 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
824
825 if (restoreTimer >= 0) {
826 mHandler.sendMessageDelayed(
827 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
828 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700829
Robert Greenwalta52c75a2009-08-19 20:19:33 -0700830 if ((ni.isConnectedOrConnecting() == true) &&
831 !network.isTeardownRequested()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700832 if (ni.isConnected() == true) {
833 // add the pid-specific dns
Robert Greenwalt3afbead2010-07-23 15:46:26 -0700834 handleDnsConfigurationChange(networkType);
Wink Savillee70c6f52010-12-03 12:01:38 -0800835 if (DBG) log("special network already active");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700836 return Phone.APN_ALREADY_ACTIVE;
837 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800838 if (DBG) log("special network already connecting");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700839 return Phone.APN_REQUEST_STARTED;
840 }
841
842 // check if the radio in play can make another contact
843 // assume if cannot for now
844
Wink Savillee70c6f52010-12-03 12:01:38 -0800845 if (DBG) log("reconnecting to special network");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700846 network.reconnect();
847 return Phone.APN_REQUEST_STARTED;
848 } else {
Robert Greenwalt5364d752010-12-15 13:26:33 -0800849 // need to remember this unsupported request so we respond appropriately on stop
850 synchronized(this) {
851 mFeatureUsers.add(f);
852 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
853 // this gets used for per-pid dns when connected
854 mNetRequestersPids[usedNetworkType].add(currentPid);
855 }
856 }
Robert Greenwaltd391e892010-05-18 10:52:51 -0700857 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700858 }
859 }
860 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800861 }
862
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700863 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -0800864 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -0700865 enforceChangePermission();
866
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700867 int pid = getCallingPid();
868 int uid = getCallingUid();
869
870 FeatureUser u = null;
871 boolean found = false;
872
873 synchronized(this) {
874 for (int i = 0; i < mFeatureUsers.size() ; i++) {
875 u = (FeatureUser)mFeatureUsers.get(i);
876 if (uid == u.mUid && pid == u.mPid &&
877 networkType == u.mNetworkType &&
878 TextUtils.equals(feature, u.mFeature)) {
879 found = true;
880 break;
881 }
882 }
883 }
884 if (found && u != null) {
885 // stop regardless of how many other time this proc had called start
886 return stopUsingNetworkFeature(u, true);
887 } else {
888 // none found!
Wink Savillee70c6f52010-12-03 12:01:38 -0800889 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700890 return 1;
891 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700892 }
893
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700894 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
895 int networkType = u.mNetworkType;
896 String feature = u.mFeature;
897 int pid = u.mPid;
898 int uid = u.mUid;
899
900 NetworkStateTracker tracker = null;
901 boolean callTeardown = false; // used to carry our decision outside of sync block
902
Robert Greenwalt2034b912009-08-12 16:08:25 -0700903 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800904 log("stopUsingNetworkFeature for net " + networkType +
Robert Greenwalt2034b912009-08-12 16:08:25 -0700905 ": " + feature);
906 }
Robert Greenwalt28f43012009-10-06 17:52:40 -0700907
The Android Open Source Project28527d22009-03-03 19:31:44 -0800908 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
909 return -1;
910 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700911
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700912 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
913 // sync block
914 synchronized(this) {
915 // check if this process still has an outstanding start request
916 if (!mFeatureUsers.contains(u)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800917 if (DBG) log("ignoring - this process has no outstanding requests");
Robert Greenwalt2034b912009-08-12 16:08:25 -0700918 return 1;
919 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700920 u.unlinkDeathRecipient();
921 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
922 // If we care about duplicate requests, check for that here.
923 //
924 // This is done to support the extension of a request - the app
925 // can request we start the network feature again and renew the
926 // auto-shutoff delay. Normal "stop" calls from the app though
927 // do not pay attention to duplicate requests - in effect the
928 // API does not refcount and a single stop will counter multiple starts.
929 if (ignoreDups == false) {
930 for (int i = 0; i < mFeatureUsers.size() ; i++) {
931 FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
932 if (x.mUid == u.mUid && x.mPid == u.mPid &&
933 x.mNetworkType == u.mNetworkType &&
934 TextUtils.equals(x.mFeature, u.mFeature)) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800935 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700936 return 1;
937 }
938 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700939 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700940
941 // TODO - move to MobileDataStateTracker
942 int usedNetworkType = networkType;
943 if (networkType == ConnectivityManager.TYPE_MOBILE) {
Wink Savillef6b76692011-02-24 17:58:51 -0800944 usedNetworkType = convertFeatureToNetworkType(feature);
945 if (usedNetworkType < 0) {
946 usedNetworkType = networkType;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700947 }
948 }
949 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700950 if (tracker == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800951 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700952 return -1;
953 }
954 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700955 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700956 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt0ca68a02009-12-17 14:54:59 -0800957 reassessPidDns(pid, true);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700958 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800959 if (DBG) log("not tearing down special network - " +
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700960 "others still using it");
961 return 1;
962 }
963 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -0800964 } else {
965 if (DBG) log("not a known feature - dropping");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700966 }
967 }
Wink Savillee70c6f52010-12-03 12:01:38 -0800968 if (DBG) log("Doing network teardown");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -0700969 if (callTeardown) {
970 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700971 return 1;
972 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -0700973 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700974 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800975 }
976
977 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700978 * @deprecated use requestRouteToHostAddress instead
979 *
The Android Open Source Project28527d22009-03-03 19:31:44 -0800980 * Ensure that a network route exists to deliver traffic to the specified
981 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700982 * @param networkType the type of the network over which traffic to the
983 * specified host is to be routed
984 * @param hostAddress the IP address of the host to which the route is
985 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -0800986 * @return {@code true} on success, {@code false} on failure
987 */
988 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700989 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
990
991 if (inetAddress == null) {
992 return false;
993 }
994
995 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
996 }
997
998 /**
999 * Ensure that a network route exists to deliver traffic to the specified
1000 * host via the specified network interface.
1001 * @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
1005 * @return {@code true} on success, {@code false} on failure
1006 */
1007 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001008 enforceChangePermission();
1009 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1010 return false;
1011 }
1012 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001013
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001014 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1015 tracker.isTeardownRequested()) {
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001016 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001017 log("requestRouteToHostAddress on down network " +
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001018 "(" + networkType + ") - dropped");
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001019 }
1020 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001021 }
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001022 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001023 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001024 return addHostRoute(tracker, addr, 0);
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001025 } catch (UnknownHostException e) {}
1026 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001027 }
1028
1029 /**
1030 * Ensure that a network route exists to deliver traffic to the specified
1031 * host via the mobile data network.
1032 * @param hostAddress the IP address of the host to which the route is desired,
1033 * in network byte order.
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001034 * TODO - deprecate
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001035 * @return {@code true} on success, {@code false} on failure
1036 */
Robert Greenwaltbd492212011-05-06 17:10:53 -07001037 private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress, int cycleCount) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001038 LinkProperties lp = nt.getLinkProperties();
1039 if ((lp == null) || (hostAddress == null)) return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001040
Robert Greenwaltbd492212011-05-06 17:10:53 -07001041 String interfaceName = lp.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001042 if (DBG) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001043 log("Requested host route to " + hostAddress + "(" + interfaceName + "), cycleCount=" +
1044 cycleCount);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001045 }
Robert Greenwaltbd492212011-05-06 17:10:53 -07001046 if (interfaceName == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001047 if (DBG) loge("addHostRoute failed due to null interface name");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001048 return false;
1049 }
Robert Greenwaltbd492212011-05-06 17:10:53 -07001050
1051 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), hostAddress);
Robert Greenwalt355205c2011-05-10 15:05:02 -07001052 InetAddress gatewayAddress = null;
Robert Greenwaltbd492212011-05-06 17:10:53 -07001053 if (bestRoute != null) {
Robert Greenwalt355205c2011-05-10 15:05:02 -07001054 gatewayAddress = bestRoute.getGateway();
Robert Greenwaltbd492212011-05-06 17:10:53 -07001055 // if the best route is ourself, don't relf-reference, just add the host route
Robert Greenwalt355205c2011-05-10 15:05:02 -07001056 if (hostAddress.equals(gatewayAddress)) gatewayAddress = null;
Robert Greenwaltbd492212011-05-06 17:10:53 -07001057 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001058 if (gatewayAddress != null) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001059 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1060 loge("Error adding hostroute - too much recursion");
1061 return false;
1062 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001063 if (!addHostRoute(nt, gatewayAddress, cycleCount+1)) return false;
Robert Greenwaltbd492212011-05-06 17:10:53 -07001064 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001065
1066 RouteInfo route = RouteInfo.makeHostRoute(hostAddress, gatewayAddress);
1067
1068 try {
1069 mNetd.addRoute(interfaceName, route);
1070 return true;
1071 } catch (Exception ex) {
1072 return false;
1073 }
Robert Greenwaltbd492212011-05-06 17:10:53 -07001074 }
1075
1076 // TODO support the removal of single host routes. Keep a ref count of them so we
1077 // aren't over-zealous
1078 private boolean removeHostRoute(NetworkStateTracker nt, InetAddress hostAddress) {
1079 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001080 }
1081
1082 /**
1083 * @see ConnectivityManager#getBackgroundDataSetting()
1084 */
1085 public boolean getBackgroundDataSetting() {
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001086 return mBackgroundDataEnabled.get();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001087 }
Robert Greenwalt0659da32009-07-16 17:21:39 -07001088
The Android Open Source Project28527d22009-03-03 19:31:44 -08001089 /**
1090 * @see ConnectivityManager#setBackgroundDataSetting(boolean)
1091 */
1092 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
1093 mContext.enforceCallingOrSelfPermission(
1094 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
1095 "ConnectivityService");
Robert Greenwalt0659da32009-07-16 17:21:39 -07001096
Robert Greenwaltd62c7002010-12-29 16:15:02 -08001097 mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1098
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001099 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1100 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1101 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001102
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001103 private void handleSetBackgroundData(boolean enabled) {
Robert Greenwalt0ffdef12011-02-25 13:44:09 -08001104 Settings.Secure.putInt(mContext.getContentResolver(),
1105 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1106 Intent broadcast = new Intent(
1107 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1108 mContext.sendBroadcast(broadcast);
Robert Greenwalt0659da32009-07-16 17:21:39 -07001109 }
1110
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001111 /**
1112 * @see ConnectivityManager#getMobileDataEnabled()
1113 */
1114 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001115 // TODO: This detail should probably be in DataConnectionTracker's
1116 // which is where we store the value and maybe make this
1117 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001118 enforceAccessPermission();
1119 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1120 Settings.Secure.MOBILE_DATA, 1) == 1;
Wink Savillee70c6f52010-12-03 12:01:38 -08001121 if (DBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001122 return retVal;
1123 }
1124
Robert Greenwalt34848c02011-03-25 13:09:25 -07001125 public void setDataDependency(int networkType, boolean met) {
1126 enforceChangePermission();
1127 if (DBG) {
1128 log("setDataDependency(" + networkType + ", " + met + ")");
1129 }
1130 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1131 (met ? ENABLED : DISABLED), networkType));
1132 }
1133
1134 private void handleSetDependencyMet(int networkType, boolean met) {
1135 if (mNetTrackers[networkType] != null) {
1136 if (DBG) {
1137 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1138 }
1139 mNetTrackers[networkType].setDependencyMet(met);
1140 }
1141 }
1142
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001143 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1144 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001145 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001146 // only someone like NPMS should only be calling us
Jeff Sharkey4434b0b2011-06-16 13:04:20 -07001147 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001148
1149 if (LOGD_RULES) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001150 Slog.d(TAG, "onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001151 }
1152
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001153 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001154 // skip update when we've already applied rules
1155 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1156 if (oldRules == uidRules) return;
1157
1158 mUidRules.put(uid, uidRules);
1159 }
1160
1161 // TODO: dispatch into NMS to push rules towards kernel module
1162 // TODO: notify UID when it has requested targeted updates
1163 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001164
1165 @Override
1166 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1167 // only someone like NPMS should only be calling us
1168 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1169
1170 if (LOGD_RULES) {
1171 Slog.d(TAG,
1172 "onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1173 }
1174
1175 synchronized (mRulesLock) {
1176 mMeteredIfaces.clear();
1177 for (String iface : meteredIfaces) {
1178 mMeteredIfaces.add(iface);
1179 }
1180 }
1181 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001182 };
1183
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001184 /**
1185 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1186 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001187 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001188 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001189 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001190
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001191 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001192 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001193 }
1194
1195 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001196 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1197 if (DBG) {
1198 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001199 }
Wink Savilleb9024c62010-12-07 10:31:02 -08001200 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001201 }
1202 }
1203
The Android Open Source Project28527d22009-03-03 19:31:44 -08001204 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001205 mContext.enforceCallingOrSelfPermission(
1206 android.Manifest.permission.ACCESS_NETWORK_STATE,
1207 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001208 }
1209
1210 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001211 mContext.enforceCallingOrSelfPermission(
1212 android.Manifest.permission.CHANGE_NETWORK_STATE,
1213 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001214 }
1215
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001216 // TODO Make this a special check when it goes public
1217 private void enforceTetherChangePermission() {
1218 mContext.enforceCallingOrSelfPermission(
1219 android.Manifest.permission.CHANGE_NETWORK_STATE,
1220 "ConnectivityService");
1221 }
1222
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001223 private void enforceTetherAccessPermission() {
1224 mContext.enforceCallingOrSelfPermission(
1225 android.Manifest.permission.ACCESS_NETWORK_STATE,
1226 "ConnectivityService");
1227 }
1228
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001229 private void enforceConnectivityInternalPermission() {
1230 mContext.enforceCallingOrSelfPermission(
1231 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1232 "ConnectivityService");
1233 }
1234
The Android Open Source Project28527d22009-03-03 19:31:44 -08001235 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001236 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1237 * network, we ignore it. If it is for the active network, we send out a
1238 * broadcast. But first, we check whether it might be possible to connect
1239 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001240 * @param info the {@code NetworkInfo} for the network
1241 */
1242 private void handleDisconnect(NetworkInfo info) {
1243
Robert Greenwalt2034b912009-08-12 16:08:25 -07001244 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001245
Robert Greenwalt2034b912009-08-12 16:08:25 -07001246 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001247 /*
1248 * If the disconnected network is not the active one, then don't report
1249 * this as a loss of connectivity. What probably happened is that we're
1250 * getting the disconnect for a network that we explicitly disabled
1251 * in accordance with network preference policies.
1252 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001253 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001254 List pids = mNetRequestersPids[prevNetType];
1255 for (int i = 0; i<pids.size(); i++) {
1256 Integer pid = (Integer)pids.get(i);
1257 // will remove them because the net's no longer connected
1258 // need to do this now as only now do we know the pids and
1259 // can properly null things that are no longer referenced.
1260 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001261 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001262 }
1263
The Android Open Source Project28527d22009-03-03 19:31:44 -08001264 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1265 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1266 if (info.isFailover()) {
1267 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1268 info.setFailover(false);
1269 }
1270 if (info.getReason() != null) {
1271 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1272 }
1273 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001274 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1275 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001276 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001277
Robert Greenwalt34848c02011-03-25 13:09:25 -07001278 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001279 tryFailover(prevNetType);
1280 if (mActiveDefaultNetwork != -1) {
1281 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001282 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1283 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001284 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001285 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1286 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001287 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001288 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001289
1290 // Reset interface if no other connections are using the same interface
1291 boolean doReset = true;
1292 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1293 if (linkProperties != null) {
1294 String oldIface = linkProperties.getInterfaceName();
1295 if (TextUtils.isEmpty(oldIface) == false) {
1296 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1297 if (networkStateTracker == null) continue;
1298 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1299 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1300 LinkProperties l = networkStateTracker.getLinkProperties();
1301 if (l == null) continue;
1302 if (oldIface.equals(l.getInterfaceName())) {
1303 doReset = false;
1304 break;
1305 }
1306 }
1307 }
1308 }
1309 }
1310
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001311 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001312 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001313
1314 sendStickyBroadcast(intent);
1315 /*
1316 * If the failover network is already connected, then immediately send
1317 * out a followup broadcast indicating successful failover
1318 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001319 if (mActiveDefaultNetwork != -1) {
1320 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001321 }
1322 }
1323
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001324 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001325 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001326 * If this is a default network, check if other defaults are available.
1327 * Try to reconnect on all available and let them hash it out when
1328 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001329 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001330 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001331 if (mActiveDefaultNetwork == prevNetType) {
1332 mActiveDefaultNetwork = -1;
1333 }
1334
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001335 // don't signal a reconnect for anything lower or equal priority than our
1336 // current connected default
1337 // TODO - don't filter by priority now - nice optimization but risky
1338// int currentPriority = -1;
1339// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001340// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001341// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001342 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001343 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001344 if (mNetConfigs[checkType] == null) continue;
1345 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001346
1347// Enabling the isAvailable() optimization caused mobile to not get
1348// selected if it was in the middle of error handling. Specifically
1349// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1350// would not be available and we wouldn't get connected to anything.
1351// So removing the isAvailable() optimization below for now. TODO: This
1352// optimization should work and we need to investigate why it doesn't work.
1353// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1354// complete before it is really complete.
1355// if (!mNetTrackers[checkType].isAvailable()) continue;
1356
Robert Greenwalt34848c02011-03-25 13:09:25 -07001357// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001358
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001359 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1360 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1361 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1362 checkInfo.setFailover(true);
1363 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001364 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001365 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001366 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001367 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001368 }
1369
1370 private void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001371 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1372 }
1373
1374 private void sendInetConditionBroadcast(NetworkInfo info) {
1375 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1376 }
1377
1378 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1379 Intent intent = new Intent(bcastType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001380 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1381 if (info.isFailover()) {
1382 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1383 info.setFailover(false);
1384 }
1385 if (info.getReason() != null) {
1386 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1387 }
1388 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001389 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1390 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001391 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001392 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001393 sendStickyBroadcast(intent);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001394 }
1395
1396 /**
1397 * Called when an attempt to fail over to another network has failed.
1398 * @param info the {@link NetworkInfo} for the failed network
1399 */
1400 private void handleConnectionFailure(NetworkInfo info) {
1401 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001402
Robert Greenwalt2034b912009-08-12 16:08:25 -07001403 String reason = info.getReason();
1404 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001405
Robert Greenwalte981bc52010-10-08 16:35:52 -07001406 String reasonText;
1407 if (reason == null) {
1408 reasonText = ".";
1409 } else {
1410 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001411 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001412 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001413
1414 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1415 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1416 if (getActiveNetworkInfo() == null) {
1417 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1418 }
1419 if (reason != null) {
1420 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1421 }
1422 if (extraInfo != null) {
1423 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1424 }
1425 if (info.isFailover()) {
1426 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1427 info.setFailover(false);
1428 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001429
Robert Greenwalt34848c02011-03-25 13:09:25 -07001430 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001431 tryFailover(info.getType());
1432 if (mActiveDefaultNetwork != -1) {
1433 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001434 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1435 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001436 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001437 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1438 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001439 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001440
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001441 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001442 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001443 /*
1444 * If the failover network is already connected, then immediately send
1445 * out a followup broadcast indicating successful failover
1446 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001447 if (mActiveDefaultNetwork != -1) {
1448 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001449 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001450 }
1451
1452 private void sendStickyBroadcast(Intent intent) {
1453 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08001454 if (!mSystemReady) {
1455 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001456 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08001457 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1458 mContext.sendStickyBroadcast(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001459 }
1460 }
1461
1462 void systemReady() {
1463 synchronized(this) {
1464 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001465 if (mInitialBroadcast != null) {
1466 mContext.sendStickyBroadcast(mInitialBroadcast);
1467 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001468 }
1469 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001470 // load the global proxy at startup
1471 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project28527d22009-03-03 19:31:44 -08001472 }
1473
1474 private void handleConnect(NetworkInfo info) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001475 int type = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001476
1477 // snapshot isFailover, because sendConnectedBroadcast() resets it
1478 boolean isFailover = info.isFailover();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001479 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project28527d22009-03-03 19:31:44 -08001480
Robert Greenwalt2034b912009-08-12 16:08:25 -07001481 // if this is a default net and other default is running
1482 // kill the one not preferred
Robert Greenwalt34848c02011-03-25 13:09:25 -07001483 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001484 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1485 if ((type != mNetworkPreference &&
Wink Savillef2a62832011-04-07 14:23:45 -07001486 mNetConfigs[mActiveDefaultNetwork].priority >
1487 mNetConfigs[type].priority) ||
Robert Greenwalt2034b912009-08-12 16:08:25 -07001488 mNetworkPreference == mActiveDefaultNetwork) {
1489 // don't accept this one
Wink Savillee70c6f52010-12-03 12:01:38 -08001490 if (DBG) {
1491 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001492 "to torn down network " + info.getTypeName());
Wink Savillee70c6f52010-12-03 12:01:38 -08001493 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001494 teardown(thisNet);
1495 return;
1496 } else {
1497 // tear down the other
1498 NetworkStateTracker otherNet =
1499 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08001500 if (DBG) {
1501 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07001502 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08001503 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001504 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001505 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07001506 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001507 return;
1508 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001509 }
1510 }
1511 synchronized (ConnectivityService.this) {
1512 // have a new default network, release the transition wakelock in a second
1513 // if it's held. The second pause is to allow apps to reconnect over the
1514 // new network
1515 if (mNetTransitionWakeLock.isHeld()) {
1516 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07001517 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001518 mNetTransitionWakeLockSerialNumber, 0),
1519 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001520 }
1521 }
1522 mActiveDefaultNetwork = type;
Robert Greenwalt986c7412010-09-08 15:24:47 -07001523 // this will cause us to come up initially as unconnected and switching
1524 // to connected after our normal pause unless somebody reports us as reall
1525 // disconnected
1526 mDefaultInetConditionPublished = 0;
1527 mDefaultConnectionSequence++;
1528 mInetConditionChangeInFlight = false;
1529 // Don't do this - if we never sign in stay, grey
1530 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001531 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001532 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001533 updateNetworkSettings(thisNet);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001534 handleConnectivityChange(type, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001535 sendConnectedBroadcast(info);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001536 }
1537
The Android Open Source Project28527d22009-03-03 19:31:44 -08001538 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001539 * After a change in the connectivity state of a network. We're mainly
1540 * concerned with making sure that the list of DNS servers is set up
1541 * according to which networks are connected, and ensuring that the
1542 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001543 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001544 private void handleConnectivityChange(int netType, boolean doReset) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001545 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07001546 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001547 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001548 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001549 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001550
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001551 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001552 if (mNetConfigs[netType].isDefault()) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001553 handleApplyDefaultProxy(netType);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001554 addDefaultRoute(mNetTrackers[netType]);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001555 } else {
Robert Greenwalt1e2f2862011-04-01 10:51:22 -07001556 // many radios add a default route even when we don't want one.
1557 // remove the default route unless we need it for our active network
1558 if (mActiveDefaultNetwork != -1) {
1559 LinkProperties defaultLinkProperties =
1560 mNetTrackers[mActiveDefaultNetwork].getLinkProperties();
1561 LinkProperties newLinkProperties =
1562 mNetTrackers[netType].getLinkProperties();
1563 String defaultIface = defaultLinkProperties.getInterfaceName();
1564 if (defaultIface != null &&
1565 !defaultIface.equals(newLinkProperties.getInterfaceName())) {
1566 removeDefaultRoute(mNetTrackers[netType]);
1567 }
1568 }
Michael Jurka837e3642011-03-30 19:54:08 -07001569 addPrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001570 }
1571 } else {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001572 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001573 removeDefaultRoute(mNetTrackers[netType]);
1574 } else {
1575 removePrivateDnsRoutes(mNetTrackers[netType]);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001576 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001577 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001578
1579 if (doReset) {
1580 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1581 if (linkProperties != null) {
1582 String iface = linkProperties.getInterfaceName();
1583 if (TextUtils.isEmpty(iface) == false) {
1584 if (DBG) log("resetConnections(" + iface + ")");
1585 NetworkUtils.resetConnections(iface);
1586 }
1587 }
1588 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001589 }
1590
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001591 private void addPrivateDnsRoutes(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001592 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001593 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001594 if (p == null) return;
1595 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001596
1597 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001598 log("addPrivateDnsRoutes for " + nt +
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001599 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1600 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001601 if (interfaceName != null && !privateDnsRouteSet) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001602 Collection<InetAddress> dnsList = p.getDnses();
1603 for (InetAddress dns : dnsList) {
Robert Greenwaltbd492212011-05-06 17:10:53 -07001604 addHostRoute(nt, dns, 0);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001605 }
1606 nt.privateDnsRouteSet(true);
1607 }
1608 }
1609
1610 private void removePrivateDnsRoutes(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001611 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001612 if (p == null) return;
1613 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001614 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1615 if (interfaceName != null && privateDnsRouteSet) {
1616 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001617 log("removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001618 " (" + interfaceName + ")");
1619 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001620
1621 Collection<InetAddress> dnsList = p.getDnses();
1622 for (InetAddress dns : dnsList) {
1623 if (DBG) log(" removing " + dns);
1624 RouteInfo route = RouteInfo.makeHostRoute(dns);
1625 try {
1626 mNetd.removeRoute(interfaceName, route);
1627 } catch (Exception ex) {
1628 loge("error (" + ex + ") removing dns route " + route);
1629 }
1630 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001631 nt.privateDnsRouteSet(false);
1632 }
1633 }
1634
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001635
1636 private void addDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001637 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001638 if (p == null) return;
1639 String interfaceName = p.getInterfaceName();
Robert Greenwalt5c733972011-02-09 13:56:06 -08001640 if (TextUtils.isEmpty(interfaceName)) return;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001641
Robert Greenwalt355205c2011-05-10 15:05:02 -07001642 for (RouteInfo route : p.getRoutes()) {
Robert Greenwalt5a901292011-04-28 14:28:50 -07001643 //TODO - handle non-default routes
1644 if (route.isDefaultRoute()) {
Robert Greenwalt355205c2011-05-10 15:05:02 -07001645 if (DBG) log("adding default route " + route);
Robert Greenwalt5a901292011-04-28 14:28:50 -07001646 InetAddress gateway = route.getGateway();
Robert Greenwalt355205c2011-05-10 15:05:02 -07001647 if (addHostRoute(nt, gateway, 0)) {
1648 try {
1649 mNetd.addRoute(interfaceName, route);
1650 } catch (Exception e) {
1651 loge("error adding default route " + route);
1652 continue;
1653 }
Robert Greenwalt5a901292011-04-28 14:28:50 -07001654 if (DBG) {
1655 NetworkInfo networkInfo = nt.getNetworkInfo();
1656 log("addDefaultRoute for " + networkInfo.getTypeName() +
1657 " (" + interfaceName + "), GatewayAddr=" +
1658 gateway.getHostAddress());
1659 }
Robert Greenwalt355205c2011-05-10 15:05:02 -07001660 } else {
1661 loge("error adding host route for default route " + route);
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001662 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001663 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001664 }
1665 }
1666
1667
1668 public void removeDefaultRoute(NetworkStateTracker nt) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001669 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001670 if (p == null) return;
1671 String interfaceName = p.getInterfaceName();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001672
Robert Greenwalt355205c2011-05-10 15:05:02 -07001673 if (interfaceName == null) return;
1674
1675 for (RouteInfo route : p.getRoutes()) {
1676 //TODO - handle non-default routes
1677 if (route.isDefaultRoute()) {
1678 try {
1679 mNetd.removeRoute(interfaceName, route);
1680 } catch (Exception ex) {
1681 loge("error (" + ex + ") removing default route " + route);
1682 continue;
1683 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07001684 if (DBG) {
1685 NetworkInfo networkInfo = nt.getNetworkInfo();
1686 log("removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1687 interfaceName + ")");
1688 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001689 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001690 }
1691 }
1692
1693 /**
1694 * Reads the network specific TCP buffer sizes from SystemProperties
1695 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1696 * wide use
1697 */
1698 public void updateNetworkSettings(NetworkStateTracker nt) {
1699 String key = nt.getTcpBufferSizesPropName();
1700 String bufferSizes = SystemProperties.get(key);
1701
1702 if (bufferSizes.length() == 0) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001703 loge(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001704
1705 // Setting to default values so we won't be stuck to previous values
1706 key = "net.tcp.buffersize.default";
1707 bufferSizes = SystemProperties.get(key);
1708 }
1709
1710 // Set values in kernel
1711 if (bufferSizes.length() != 0) {
1712 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001713 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001714 + "] which comes from [" + key + "]");
1715 }
1716 setBufferSize(bufferSizes);
1717 }
1718 }
1719
1720 /**
1721 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1722 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1723 *
1724 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1725 * writeMin, writeInitial, writeMax"
1726 */
1727 private void setBufferSize(String bufferSizes) {
1728 try {
1729 String[] values = bufferSizes.split(",");
1730
1731 if (values.length == 6) {
1732 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04001733 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1734 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1735 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1736 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1737 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1738 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001739 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08001740 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001741 }
1742 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001743 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001744 }
1745 }
1746
Robert Greenwalt2034b912009-08-12 16:08:25 -07001747 /**
1748 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1749 * on the highest priority active net which this process requested.
1750 * If there aren't any, clear it out
1751 */
1752 private void reassessPidDns(int myPid, boolean doBump)
1753 {
Wink Savillee70c6f52010-12-03 12:01:38 -08001754 if (DBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001755 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001756 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001757 continue;
1758 }
1759 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07001760 if (nt.getNetworkInfo().isConnected() &&
1761 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001762 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001763 if (p == null) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001764 List pids = mNetRequestersPids[i];
1765 for (int j=0; j<pids.size(); j++) {
1766 Integer pid = (Integer)pids.get(j);
1767 if (pid.intValue() == myPid) {
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001768 Collection<InetAddress> dnses = p.getDnses();
1769 writePidDns(dnses, myPid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001770 if (doBump) {
1771 bumpDns();
1772 }
1773 return;
1774 }
1775 }
1776 }
1777 }
1778 // nothing found - delete
1779 for (int i = 1; ; i++) {
1780 String prop = "net.dns" + i + "." + myPid;
1781 if (SystemProperties.get(prop).length() == 0) {
1782 if (doBump) {
1783 bumpDns();
1784 }
1785 return;
1786 }
1787 SystemProperties.set(prop, "");
1788 }
1789 }
1790
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001791 // return true if results in a change
1792 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001793 int j = 1;
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001794 boolean changed = false;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001795 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001796 String dnsString = dns.getHostAddress();
1797 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1798 changed = true;
1799 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1800 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001801 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001802 return changed;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001803 }
1804
1805 private void bumpDns() {
1806 /*
1807 * Bump the property that tells the name resolver library to reread
1808 * the DNS server list from the properties.
1809 */
1810 String propVal = SystemProperties.get("net.dnschange");
1811 int n = 0;
1812 if (propVal.length() != 0) {
1813 try {
1814 n = Integer.parseInt(propVal);
1815 } catch (NumberFormatException e) {}
1816 }
1817 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt051642b2010-11-02 14:08:23 -07001818 /*
1819 * Tell the VMs to toss their DNS caches
1820 */
1821 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1822 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08001823 /*
1824 * Connectivity events can happen before boot has completed ...
1825 */
1826 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt051642b2010-11-02 14:08:23 -07001827 mContext.sendBroadcast(intent);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001828 }
1829
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001830 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001831 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001832 NetworkStateTracker nt = mNetTrackers[netType];
1833 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07001834 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001835 if (p == null) return;
1836 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001837 boolean changed = false;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001838 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001839 int j = 1;
Robert Greenwalt94daa182010-09-01 11:34:05 -07001840 if (dnses.size() == 0 && mDefaultDns != null) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001841 String dnsString = mDefaultDns.getHostAddress();
1842 if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1843 if (DBG) {
1844 log("no dns provided - using " + dnsString);
1845 }
1846 changed = true;
1847 SystemProperties.set("net.dns1", dnsString);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001848 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001849 j++;
1850 } else {
1851 for (InetAddress dns : dnses) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001852 String dnsString = dns.getHostAddress();
1853 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1854 j++;
1855 continue;
1856 }
Robert Greenwalt94daa182010-09-01 11:34:05 -07001857 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001858 log("adding dns " + dns + " for " +
Robert Greenwalt94daa182010-09-01 11:34:05 -07001859 nt.getNetworkInfo().getTypeName());
1860 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001861 changed = true;
1862 SystemProperties.set("net.dns" + j++, dnsString);
Robert Greenwalt94daa182010-09-01 11:34:05 -07001863 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001864 }
1865 for (int k=j ; k<mNumDnsEntries; k++) {
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001866 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1867 if (DBG) log("erasing net.dns" + k);
1868 changed = true;
1869 SystemProperties.set("net.dns" + k, "");
1870 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07001871 }
1872 mNumDnsEntries = j;
1873 } else {
1874 // set per-pid dns for attached secondary nets
1875 List pids = mNetRequestersPids[netType];
1876 for (int y=0; y< pids.size(); y++) {
1877 Integer pid = (Integer)pids.get(y);
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001878 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001879 }
1880 }
Robert Greenwalt8ca88762010-12-17 15:20:36 -08001881 if (changed) bumpDns();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001882 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001883 }
1884
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001885 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001886 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1887 NETWORK_RESTORE_DELAY_PROP_NAME);
1888 if(restoreDefaultNetworkDelayStr != null &&
1889 restoreDefaultNetworkDelayStr.length() != 0) {
1890 try {
1891 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1892 } catch (NumberFormatException e) {
1893 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001894 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07001895 // if the system property isn't set, use the value for the apn type
1896 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1897
1898 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1899 (mNetConfigs[networkType] != null)) {
1900 ret = mNetConfigs[networkType].restoreTime;
1901 }
1902 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001903 }
1904
1905 @Override
1906 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001907 if (mContext.checkCallingOrSelfPermission(
1908 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001909 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001910 pw.println("Permission Denial: can't dump ConnectivityService " +
1911 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1912 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001913 return;
1914 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001915 pw.println();
1916 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001917 if (nst != null) {
1918 if (nst.getNetworkInfo().isConnected()) {
1919 pw.println("Active network: " + nst.getNetworkInfo().
1920 getTypeName());
1921 }
1922 pw.println(nst.getNetworkInfo());
1923 pw.println(nst);
1924 pw.println();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001925 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001926 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001927
1928 pw.println("Network Requester Pids:");
1929 for (int net : mPriorityList) {
1930 String pidString = net + ": ";
1931 for (Object pid : mNetRequestersPids[net]) {
1932 pidString = pidString + pid.toString() + ", ";
1933 }
1934 pw.println(pidString);
1935 }
1936 pw.println();
1937
1938 pw.println("FeatureUsers:");
1939 for (Object requester : mFeatureUsers) {
1940 pw.println(requester.toString());
1941 }
1942 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001943
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001944 synchronized (this) {
1945 pw.println("NetworkTranstionWakeLock is currently " +
1946 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1947 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1948 }
1949 pw.println();
1950
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001951 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07001952
1953 if (mInetLog != null) {
1954 pw.println();
1955 pw.println("Inet condition reports:");
1956 for(int i = 0; i < mInetLog.size(); i++) {
1957 pw.println(mInetLog.get(i));
1958 }
1959 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001960 }
1961
Robert Greenwalt2034b912009-08-12 16:08:25 -07001962 // must be stateless - things change under us.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001963 private class MyHandler extends Handler {
Wink Saville775aad62010-09-02 19:23:52 -07001964 public MyHandler(Looper looper) {
1965 super(looper);
1966 }
1967
The Android Open Source Project28527d22009-03-03 19:31:44 -08001968 @Override
1969 public void handleMessage(Message msg) {
1970 NetworkInfo info;
1971 switch (msg.what) {
1972 case NetworkStateTracker.EVENT_STATE_CHANGED:
1973 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08001974 int type = info.getType();
1975 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08001976
Wink Savillee70c6f52010-12-03 12:01:38 -08001977 if (DBG) log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07001978 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08001979 state + "/" + info.getDetailedState());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001980
1981 // Connectivity state changed:
1982 // [31-13] Reserved for future use
Robert Greenwalt0659da32009-07-16 17:21:39 -07001983 // [12-9] Network subtype (for mobile network, as defined
1984 // by TelephonyManager)
1985 // [8-3] Detailed state ordinal (as defined by
1986 // NetworkInfo.DetailedState)
The Android Open Source Project28527d22009-03-03 19:31:44 -08001987 // [2-0] Network type (as defined by ConnectivityManager)
1988 int eventLogParam = (info.getType() & 0x7) |
1989 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1990 (info.getSubtype() << 9);
Doug Zongker2fc96232009-12-04 10:31:43 -08001991 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt0659da32009-07-16 17:21:39 -07001992 eventLogParam);
1993
1994 if (info.getDetailedState() ==
1995 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001996 handleConnectionFailure(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001997 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001998 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08001999 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002000 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002001 // the logic here is, handle SUSPENDED the same as
2002 // DISCONNECTED. The only difference being we are
2003 // broadcasting an intent with NetworkInfo that's
2004 // suspended. This allows the applications an
2005 // opportunity to handle DISCONNECTED and SUSPENDED
2006 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002007 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002008 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002009 handleConnect(info);
2010 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002011 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002012 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002013 info = (NetworkInfo) msg.obj;
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002014 handleConnectivityChange(info.getType(), true);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002015 break;
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002016 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002017 String causedBy = null;
2018 synchronized (ConnectivityService.this) {
2019 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2020 mNetTransitionWakeLock.isHeld()) {
2021 mNetTransitionWakeLock.release();
2022 causedBy = mNetTransitionWakeLockCausedBy;
2023 }
2024 }
2025 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002026 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002027 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002028 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002029 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002030 FeatureUser u = (FeatureUser)msg.obj;
2031 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002032 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002033 case EVENT_INET_CONDITION_CHANGE:
2034 {
2035 int netType = msg.arg1;
2036 int condition = msg.arg2;
2037 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002038 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002039 }
2040 case EVENT_INET_CONDITION_HOLD_END:
2041 {
2042 int netType = msg.arg1;
2043 int sequence = msg.arg2;
2044 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002045 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002046 }
2047 case EVENT_SET_NETWORK_PREFERENCE:
2048 {
2049 int preference = msg.arg1;
2050 handleSetNetworkPreference(preference);
2051 break;
2052 }
2053 case EVENT_SET_BACKGROUND_DATA:
2054 {
2055 boolean enabled = (msg.arg1 == ENABLED);
2056 handleSetBackgroundData(enabled);
2057 break;
2058 }
2059 case EVENT_SET_MOBILE_DATA:
2060 {
2061 boolean enabled = (msg.arg1 == ENABLED);
2062 handleSetMobileData(enabled);
2063 break;
2064 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002065 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2066 {
2067 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002068 break;
2069 }
2070 case EVENT_SET_DEPENDENCY_MET:
2071 {
2072 boolean met = (msg.arg1 == ENABLED);
2073 handleSetDependencyMet(msg.arg2, met);
2074 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002075 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002076 }
2077 }
2078 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002079
2080 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002081 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002082 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002083
2084 if (isTetheringSupported()) {
2085 return mTethering.tether(iface);
2086 } else {
2087 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2088 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002089 }
2090
2091 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002092 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002093 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002094
2095 if (isTetheringSupported()) {
2096 return mTethering.untether(iface);
2097 } else {
2098 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2099 }
2100 }
2101
2102 // javadoc from interface
2103 public int getLastTetherError(String iface) {
2104 enforceTetherAccessPermission();
2105
2106 if (isTetheringSupported()) {
2107 return mTethering.getLastTetherError(iface);
2108 } else {
2109 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2110 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002111 }
2112
2113 // TODO - proper iface API for selection by property, inspection, etc
2114 public String[] getTetherableUsbRegexs() {
2115 enforceTetherAccessPermission();
2116 if (isTetheringSupported()) {
2117 return mTethering.getTetherableUsbRegexs();
2118 } else {
2119 return new String[0];
2120 }
2121 }
2122
2123 public String[] getTetherableWifiRegexs() {
2124 enforceTetherAccessPermission();
2125 if (isTetheringSupported()) {
2126 return mTethering.getTetherableWifiRegexs();
2127 } else {
2128 return new String[0];
2129 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002130 }
2131
Danica Chang96567052010-08-11 14:54:43 -07002132 public String[] getTetherableBluetoothRegexs() {
2133 enforceTetherAccessPermission();
2134 if (isTetheringSupported()) {
2135 return mTethering.getTetherableBluetoothRegexs();
2136 } else {
2137 return new String[0];
2138 }
2139 }
2140
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002141 // TODO - move iface listing, queries, etc to new module
2142 // javadoc from interface
2143 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002144 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002145 return mTethering.getTetherableIfaces();
2146 }
2147
2148 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002149 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002150 return mTethering.getTetheredIfaces();
2151 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002152
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002153 public String[] getTetheringErroredIfaces() {
2154 enforceTetherAccessPermission();
2155 return mTethering.getErroredIfaces();
2156 }
2157
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002158 // if ro.tether.denied = true we default to no tethering
2159 // gservices could set the secure setting to 1 though to enable it on a build where it
2160 // had previously been turned off.
2161 public boolean isTetheringSupported() {
2162 enforceTetherAccessPermission();
2163 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002164 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2165 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2166 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002167 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002168
2169 // An API NetworkStateTrackers can call when they lose their network.
2170 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2171 // whichever happens first. The timer is started by the first caller and not
2172 // restarted by subsequent callers.
2173 public void requestNetworkTransitionWakelock(String forWhom) {
2174 enforceConnectivityInternalPermission();
2175 synchronized (this) {
2176 if (mNetTransitionWakeLock.isHeld()) return;
2177 mNetTransitionWakeLockSerialNumber++;
2178 mNetTransitionWakeLock.acquire();
2179 mNetTransitionWakeLockCausedBy = forWhom;
2180 }
2181 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002182 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002183 mNetTransitionWakeLockSerialNumber, 0),
2184 mNetTransitionWakeLockTimeout);
2185 return;
2186 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07002187
Robert Greenwalt986c7412010-09-08 15:24:47 -07002188 // 100 percent is full good, 0 is full bad.
2189 public void reportInetCondition(int networkType, int percentage) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002190 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07002191 mContext.enforceCallingOrSelfPermission(
2192 android.Manifest.permission.STATUS_BAR,
2193 "ConnectivityService");
2194
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002195 if (DBG) {
2196 int pid = getCallingPid();
2197 int uid = getCallingUid();
2198 String s = pid + "(" + uid + ") reports inet is " +
2199 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2200 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2201 mInetLog.add(s);
2202 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2203 mInetLog.remove(0);
2204 }
2205 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002206 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002207 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2208 }
2209
2210 private void handleInetConditionChange(int netType, int condition) {
2211 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002212 log("Inet connectivity change, net=" +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002213 netType + ", condition=" + condition +
2214 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2215 }
2216 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002217 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002218 return;
2219 }
2220 if (mActiveDefaultNetwork != netType) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002221 if (DBG) log("given net not default - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002222 return;
2223 }
2224 mDefaultInetCondition = condition;
2225 int delay;
2226 if (mInetConditionChangeInFlight == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002227 if (DBG) log("starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002228 // setup a new hold to debounce this
2229 if (mDefaultInetCondition > 50) {
2230 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2231 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2232 } else {
2233 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2234 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2235 }
2236 mInetConditionChangeInFlight = true;
2237 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2238 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2239 } else {
2240 // we've set the new condition, when this hold ends that will get
2241 // picked up
Wink Savillee70c6f52010-12-03 12:01:38 -08002242 if (DBG) log("currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002243 }
2244 }
2245
2246 private void handleInetConditionHoldEnd(int netType, int sequence) {
2247 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002248 log("Inet hold end, net=" + netType +
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002249 ", condition =" + mDefaultInetCondition +
2250 ", published condition =" + mDefaultInetConditionPublished);
2251 }
2252 mInetConditionChangeInFlight = false;
2253
2254 if (mActiveDefaultNetwork == -1) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002255 if (DBG) log("no active default network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002256 return;
2257 }
2258 if (mDefaultConnectionSequence != sequence) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002259 if (DBG) log("event hold for obsolete network - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002260 return;
2261 }
2262 if (mDefaultInetConditionPublished == mDefaultInetCondition) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002263 if (DBG) log("no change in condition - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002264 return;
2265 }
2266 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2267 if (networkInfo.isConnected() == false) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002268 if (DBG) log("default network not connected - aborting");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002269 return;
2270 }
2271 mDefaultInetConditionPublished = mDefaultInetCondition;
2272 sendInetConditionBroadcast(networkInfo);
2273 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002274 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002275
2276 public synchronized ProxyProperties getProxy() {
2277 if (mGlobalProxy != null) return mGlobalProxy;
2278 if (mDefaultProxy != null) return mDefaultProxy;
2279 return null;
2280 }
2281
2282 public void setGlobalProxy(ProxyProperties proxyProperties) {
2283 enforceChangePermission();
2284 synchronized (mGlobalProxyLock) {
2285 if (proxyProperties == mGlobalProxy) return;
2286 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2287 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2288
2289 String host = "";
2290 int port = 0;
2291 String exclList = "";
2292 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2293 mGlobalProxy = new ProxyProperties(proxyProperties);
2294 host = mGlobalProxy.getHost();
2295 port = mGlobalProxy.getPort();
2296 exclList = mGlobalProxy.getExclusionList();
2297 } else {
2298 mGlobalProxy = null;
2299 }
2300 ContentResolver res = mContext.getContentResolver();
2301 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2302 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002303 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002304 exclList);
2305 }
2306
2307 if (mGlobalProxy == null) {
2308 proxyProperties = mDefaultProxy;
2309 }
2310 sendProxyBroadcast(proxyProperties);
2311 }
2312
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002313 private void loadGlobalProxy() {
2314 ContentResolver res = mContext.getContentResolver();
2315 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2316 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2317 String exclList = Settings.Secure.getString(res,
2318 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2319 if (!TextUtils.isEmpty(host)) {
2320 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2321 synchronized (mGlobalProxyLock) {
2322 mGlobalProxy = proxyProperties;
2323 }
2324 }
2325 }
2326
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002327 public ProxyProperties getGlobalProxy() {
2328 synchronized (mGlobalProxyLock) {
2329 return mGlobalProxy;
2330 }
2331 }
2332
2333 private void handleApplyDefaultProxy(int type) {
2334 // check if new default - push it out to all VM if so
2335 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2336 synchronized (this) {
2337 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2338 if (mDefaultProxy == proxy) return;
2339 if (!TextUtils.isEmpty(proxy.getHost())) {
2340 mDefaultProxy = proxy;
2341 } else {
2342 mDefaultProxy = null;
2343 }
2344 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002345 if (DBG) log("changing default proxy to " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002346 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2347 if (mGlobalProxy != null) return;
2348 sendProxyBroadcast(proxy);
2349 }
2350
2351 private void handleDeprecatedGlobalHttpProxy() {
2352 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2353 Settings.Secure.HTTP_PROXY);
2354 if (!TextUtils.isEmpty(proxy)) {
2355 String data[] = proxy.split(":");
2356 String proxyHost = data[0];
2357 int proxyPort = 8080;
2358 if (data.length > 1) {
2359 try {
2360 proxyPort = Integer.parseInt(data[1]);
2361 } catch (NumberFormatException e) {
2362 return;
2363 }
2364 }
2365 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2366 setGlobalProxy(p);
2367 }
2368 }
2369
2370 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08002371 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Wink Savillee70c6f52010-12-03 12:01:38 -08002372 log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002373 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08002374 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2375 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002376 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwaltd93dc8f2010-12-06 11:29:17 -08002377 mContext.sendStickyBroadcast(intent);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002378 }
2379
2380 private static class SettingsObserver extends ContentObserver {
2381 private int mWhat;
2382 private Handler mHandler;
2383 SettingsObserver(Handler handler, int what) {
2384 super(handler);
2385 mHandler = handler;
2386 mWhat = what;
2387 }
2388
2389 void observe(Context context) {
2390 ContentResolver resolver = context.getContentResolver();
2391 resolver.registerContentObserver(Settings.Secure.getUriFor(
2392 Settings.Secure.HTTP_PROXY), false, this);
2393 }
2394
2395 @Override
2396 public void onChange(boolean selfChange) {
2397 mHandler.obtainMessage(mWhat).sendToTarget();
2398 }
2399 }
Wink Savillee70c6f52010-12-03 12:01:38 -08002400
2401 private void log(String s) {
2402 Slog.d(TAG, s);
2403 }
2404
2405 private void loge(String s) {
2406 Slog.e(TAG, s);
2407 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002408
Wink Savillef6b76692011-02-24 17:58:51 -08002409 int convertFeatureToNetworkType(String feature){
2410 int networkType = -1;
2411 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2412 networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2413 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2414 networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2415 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2416 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2417 networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2418 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2419 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2420 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2421 networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2422 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2423 networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2424 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2425 networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2426 }
2427 return networkType;
2428 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002429
2430 private static <T> T checkNotNull(T value, String message) {
2431 if (value == null) {
2432 throw new NullPointerException(message);
2433 }
2434 return value;
2435 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002436
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002437 /**
2438 * Protect a socket from VPN routing rules. This method is used by
2439 * VpnBuilder and not available in ConnectivityManager. Permission
2440 * checks are done in Vpn class.
2441 * @hide
2442 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002443 @Override
2444 public void protectVpn(ParcelFileDescriptor socket) {
2445 mVpn.protect(socket, getDefaultInterface());
2446 }
2447
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002448 /**
2449 * Prepare for a VPN application. This method is used by VpnDialogs
2450 * and not available in ConnectivityManager. Permission checks are
2451 * done in Vpn class.
2452 * @hide
2453 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002454 @Override
2455 public String prepareVpn(String packageName) {
2456 return mVpn.prepare(packageName);
2457 }
2458
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002459 /**
2460 * Configure a TUN interface and return its file descriptor. Parameters
2461 * are encoded and opaque to this class. This method is used by VpnBuilder
2462 * and not available in ConnectivityManager. Permission checks are done
2463 * in Vpn class.
2464 * @hide
2465 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002466 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07002467 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07002468 return mVpn.establish(config);
2469 }
2470
2471 private String getDefaultInterface() {
2472 if (ConnectivityManager.isNetworkTypeValid(mActiveDefaultNetwork)) {
2473 NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
2474 if (tracker != null) {
2475 LinkProperties properties = tracker.getLinkProperties();
2476 if (properties != null) {
2477 return properties.getInterfaceName();
2478 }
2479 }
2480 }
2481 throw new IllegalStateException("No default interface");
2482 }
2483
2484 /**
2485 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2486 * through NetworkStateTracker since it works differently. For example, it
2487 * needs to override DNS servers but never takes the default routes. It
2488 * relies on another data network, and it could keep existing connections
2489 * alive after reconnecting, switching between networks, or even resuming
2490 * from deep sleep. Calls from applications should be done synchronously
2491 * to avoid race conditions. As these are all hidden APIs, refactoring can
2492 * be done whenever a better abstraction is developed.
2493 */
2494 public class VpnCallback {
2495
2496 private VpnCallback() {
2497 }
2498
2499 public synchronized void override(String[] dnsServers) {
2500 // TODO: override DNS servers and http proxy.
2501 }
2502
2503 public synchronized void restore() {
2504 // TODO: restore VPN changes.
2505 }
2506 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002507}