blob: e28c7151795ee1bafc4d80e80a92686db377908f [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey1a303952011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
21import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070022import static android.net.ConnectivityManager.isNetworkTypeValid;
23import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070024import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080026import android.bluetooth.BluetoothTetheringDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.content.ContentResolver;
28import android.content.Context;
29import android.content.Intent;
30import android.content.pm.PackageManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070031import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080033import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080034import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.net.IConnectivityManager;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070036import android.net.INetworkPolicyListener;
37import android.net.INetworkPolicyManager;
Wink Savillec9822c52011-07-14 12:23:28 -070038import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080039import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070040import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070042import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070044import android.net.NetworkInfo.DetailedState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070045import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070046import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070048import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070049import android.net.Proxy;
50import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070051import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.wifi.WifiStateTracker;
53import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040054import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070056import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070057import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070058import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.Looper;
60import android.os.Message;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070061import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070062import android.os.PowerManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070063import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.os.ServiceManager;
65import android.os.SystemProperties;
66import android.provider.Settings;
Robert Greenwalt42acef32009-08-12 16:08:25 -070067import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080069import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070070import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
Chia-chi Yeh2e467642011-07-04 03:23:12 -070072import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070073import com.android.internal.net.VpnConfig;
Robert Greenwalt42acef32009-08-12 16:08:25 -070074import com.android.internal.telephony.Phone;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080075import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070076import com.android.server.connectivity.Vpn;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070077import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070078import com.google.android.collect.Sets;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -080079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -070081import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -070083import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -070084import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070085import java.net.InetAddress;
86import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -070087import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070088import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -070089import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -070090import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070091import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -070092import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
94/**
95 * @hide
96 */
97public class ConnectivityService extends IConnectivityManager.Stub {
98
Robert Greenwaltba175a52010-10-05 19:12:26 -070099 private static final boolean DBG = true;
Wink Savillec9acde92011-09-21 11:05:43 -0700100 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private static final String TAG = "ConnectivityService";
102
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700103 private static final boolean LOGD_RULES = false;
104
Robert Greenwalt42acef32009-08-12 16:08:25 -0700105 // how long to wait before switching back to a radio's default network
106 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
107 // system property that can override the above value
108 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
109 "android.telephony.apn-restore";
110
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700111 // used in recursive route setting to add gateways for the host for which
112 // a host route was requested.
113 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
114
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800115 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800116 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800117
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700118 private Vpn mVpn;
119
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700120 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
121 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700122 /** Currently active network rules by UID. */
123 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700124 /** Set of ifaces that are costly. */
125 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 /**
128 * Sometimes we want to refer to the individual network state
129 * trackers separately, and sometimes we just want to treat them
130 * abstractly.
131 */
132 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700133
134 /**
Wink Savillee8222252011-07-13 13:44:13 -0700135 * The link properties that define the current links
136 */
137 private LinkProperties mCurrentLinkProperties[];
138
139 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700140 * A per Net list of the PID's that requested access to the net
141 * used both as a refcount and for per-PID DNS selection
142 */
143 private List mNetRequestersPids[];
144
Robert Greenwalt42acef32009-08-12 16:08:25 -0700145 // priority order of the nettrackers
146 // (excluding dynamically set mNetworkPreference)
147 // TODO - move mNetworkTypePreference into this
148 private int[] mPriorityList;
149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 private Context mContext;
151 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700152 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700153 // 0 is full bad, 100 is full good
154 private int mDefaultInetCondition = 0;
155 private int mDefaultInetConditionPublished = 0;
156 private boolean mInetConditionChangeInFlight = false;
157 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700159 private Object mDnsLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700161 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
163 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700164 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700166 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700167 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700168
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700169 private static final int ENABLED = 1;
170 private static final int DISABLED = 0;
171
172 // Share the event space with NetworkStateTracker (which can't see this
173 // internal class but sends us events). If you change these, change
174 // NetworkStateTracker.java too.
175 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
176 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
177
178 /**
179 * used internally as a delayed event to make us switch back to the
180 * default network
181 */
182 private static final int EVENT_RESTORE_DEFAULT_NETWORK =
183 MAX_NETWORK_STATE_TRACKER_EVENT + 1;
184
185 /**
186 * used internally to change our mobile data enabled flag
187 */
188 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
189 MAX_NETWORK_STATE_TRACKER_EVENT + 2;
190
191 /**
192 * used internally to change our network preference setting
193 * arg1 = networkType to prefer
194 */
195 private static final int EVENT_SET_NETWORK_PREFERENCE =
196 MAX_NETWORK_STATE_TRACKER_EVENT + 3;
197
198 /**
199 * used internally to synchronize inet condition reports
200 * arg1 = networkType
201 * arg2 = condition (0 bad, 100 good)
202 */
203 private static final int EVENT_INET_CONDITION_CHANGE =
204 MAX_NETWORK_STATE_TRACKER_EVENT + 4;
205
206 /**
207 * used internally to mark the end of inet condition hold periods
208 * arg1 = networkType
209 */
210 private static final int EVENT_INET_CONDITION_HOLD_END =
211 MAX_NETWORK_STATE_TRACKER_EVENT + 5;
212
213 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700214 * used internally to set enable/disable cellular data
215 * arg1 = ENBALED or DISABLED
216 */
217 private static final int EVENT_SET_MOBILE_DATA =
218 MAX_NETWORK_STATE_TRACKER_EVENT + 7;
219
Robert Greenwaltf3331232010-09-24 14:32:21 -0700220 /**
221 * used internally to clear a wakelock when transitioning
222 * from one net to another
223 */
224 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
225 MAX_NETWORK_STATE_TRACKER_EVENT + 8;
226
Robert Greenwalt434203a2010-10-11 16:00:27 -0700227 /**
228 * used internally to reload global proxy settings
229 */
230 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
231 MAX_NETWORK_STATE_TRACKER_EVENT + 9;
232
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700233 /**
234 * used internally to set external dependency met/unmet
235 * arg1 = ENABLED (met) or DISABLED (unmet)
236 * arg2 = NetworkType
237 */
238 private static final int EVENT_SET_DEPENDENCY_MET =
239 MAX_NETWORK_STATE_TRACKER_EVENT + 10;
240
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700241 /**
242 * used internally to restore DNS properties back to the
243 * default network
244 */
245 private static final int EVENT_RESTORE_DNS =
246 MAX_NETWORK_STATE_TRACKER_EVENT + 11;
247
Wink Saville2b30afd2011-08-05 11:40:22 -0700248 /**
Wink Saville628b0852011-08-04 15:01:58 -0700249 * used internally to send a sticky broadcast delayed.
250 */
251 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT =
Wink Saville2b30afd2011-08-05 11:40:22 -0700252 MAX_NETWORK_STATE_TRACKER_EVENT + 12;
Wink Saville628b0852011-08-04 15:01:58 -0700253
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700254 /**
255 * Used internally to
256 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
257 */
258 private static final int EVENT_SET_POLICY_DATA_ENABLE = MAX_NETWORK_STATE_TRACKER_EVENT + 13;
259
Robert Greenwalt42acef32009-08-12 16:08:25 -0700260 private Handler mHandler;
261
262 // list of DeathRecipients used to make sure features are turned off when
263 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500264 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700265
Mike Lockwood0f79b542009-08-14 14:18:49 -0400266 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800267 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400268
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700269 private PowerManager.WakeLock mNetTransitionWakeLock;
270 private String mNetTransitionWakeLockCausedBy = "";
271 private int mNetTransitionWakeLockSerialNumber;
272 private int mNetTransitionWakeLockTimeout;
273
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700274 private InetAddress mDefaultDns;
275
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700276 // this collection is used to refcount the added routes - if there are none left
277 // it's time to remove the route from the route table
278 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
279
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700280 // used in DBG mode to track inet condition reports
281 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
282 private ArrayList mInetLog;
283
Robert Greenwalt434203a2010-10-11 16:00:27 -0700284 // track the current default http proxy - tell the world if we get a new one (real change)
285 private ProxyProperties mDefaultProxy = null;
286 // track the global proxy.
287 private ProxyProperties mGlobalProxy = null;
288 private final Object mGlobalProxyLock = new Object();
289
290 private SettingsObserver mSettingsObserver;
291
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700292 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700293 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700294
Robert Greenwalt511288a2009-12-07 11:33:18 -0800295 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700296 public int mSimultaneity;
297 public int mType;
298 public RadioAttributes(String init) {
299 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700300 mType = Integer.parseInt(fragments[0]);
301 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700302 }
303 }
304 RadioAttributes[] mRadioAttributes;
305
Robert Greenwalt50393202011-06-21 17:26:14 -0700306 // the set of network types that can only be enabled by system/sig apps
307 List mProtectedNetworks;
308
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700309 public ConnectivityService(
310 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800311 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800312
Wink Savillebb08caf2010-09-02 19:23:52 -0700313 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
314 handlerThread.start();
315 mHandler = new MyHandler(handlerThread.getLooper());
316
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800317 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800318 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
319 String id = Settings.Secure.getString(context.getContentResolver(),
320 Settings.Secure.ANDROID_ID);
321 if (id != null && id.length() > 0) {
322 String name = new String("android_").concat(id);
323 SystemProperties.set("net.hostname", name);
324 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800325 }
326
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700327 // read our default dns server ip
328 String dns = Settings.Secure.getString(context.getContentResolver(),
329 Settings.Secure.DEFAULT_DNS_SERVER);
330 if (dns == null || dns.length() == 0) {
331 dns = context.getResources().getString(
332 com.android.internal.R.string.config_default_dns_server);
333 }
334 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800335 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
336 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800337 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700338 }
339
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700340 mContext = checkNotNull(context, "missing Context");
341 mNetd = checkNotNull(netd, "missing INetworkManagementService");
342 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700343
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700344 try {
345 mPolicyManager.registerListener(mPolicyListener);
346 } catch (RemoteException e) {
347 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700348 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700349 }
350
351 final PowerManager powerManager = (PowerManager) context.getSystemService(
352 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700353 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
354 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
355 com.android.internal.R.integer.config_networkTransitionTimeout);
356
Robert Greenwalt42acef32009-08-12 16:08:25 -0700357 mNetTrackers = new NetworkStateTracker[
358 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700359 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700362
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700363 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700364 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700365
Robert Greenwalt42acef32009-08-12 16:08:25 -0700366 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700367 String[] raStrings = context.getResources().getStringArray(
368 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700369 for (String raString : raStrings) {
370 RadioAttributes r = new RadioAttributes(raString);
371 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800372 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700373 continue;
374 }
375 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800376 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700377 r.mType);
378 continue;
379 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700380 mRadioAttributes[r.mType] = r;
381 }
382
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700383 String[] naStrings = context.getResources().getStringArray(
384 com.android.internal.R.array.networkAttributes);
385 for (String naString : naStrings) {
386 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700387 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700388 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800389 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700390 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700391 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700392 }
Wink Saville975c8482011-04-07 14:23:45 -0700393 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800394 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700395 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700396 continue;
397 }
Wink Saville975c8482011-04-07 14:23:45 -0700398 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800399 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700400 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700401 continue;
402 }
Wink Saville975c8482011-04-07 14:23:45 -0700403 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700404 mNetworksDefined++;
405 } catch(Exception e) {
406 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700407 }
408 }
409
Robert Greenwalt50393202011-06-21 17:26:14 -0700410 mProtectedNetworks = new ArrayList<Integer>();
411 int[] protectedNetworks = context.getResources().getIntArray(
412 com.android.internal.R.array.config_protectedNetworks);
413 for (int p : protectedNetworks) {
414 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
415 mProtectedNetworks.add(p);
416 } else {
417 if (DBG) loge("Ignoring protectedNetwork " + p);
418 }
419 }
420
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700421 // high priority first
422 mPriorityList = new int[mNetworksDefined];
423 {
424 int insertionPoint = mNetworksDefined-1;
425 int currentLowest = 0;
426 int nextLowest = 0;
427 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700428 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700429 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700430 if (na.priority < currentLowest) continue;
431 if (na.priority > currentLowest) {
432 if (na.priority < nextLowest || nextLowest == 0) {
433 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700434 }
435 continue;
436 }
Wink Saville975c8482011-04-07 14:23:45 -0700437 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700438 }
439 currentLowest = nextLowest;
440 nextLowest = 0;
441 }
442 }
443
444 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
445 for (int i : mPriorityList) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700446 mNetRequestersPids[i] = new ArrayList();
447 }
448
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500449 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700450
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700451 mNumDnsEntries = 0;
452
453 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
454 && SystemProperties.get("ro.build.type").equals("eng");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 /*
456 * Create the network state trackers for Wi-Fi and mobile
457 * data. Maybe this could be done with a factory class,
458 * but it's not clear that it's worth it, given that
459 * the number of different network types is not going
460 * to change very often.
461 */
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700462 for (int netType : mPriorityList) {
Wink Saville975c8482011-04-07 14:23:45 -0700463 switch (mNetConfigs[netType].radio) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700464 case ConnectivityManager.TYPE_WIFI:
repo syncaea743a2011-07-29 23:55:49 -0700465 mNetTrackers[netType] = new WifiStateTracker(netType,
466 mNetConfigs[netType].name);
467 mNetTrackers[netType].startMonitoring(context, mHandler);
468 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700469 case ConnectivityManager.TYPE_MOBILE:
Wink Savillec7a98342010-08-13 16:11:42 -0700470 mNetTrackers[netType] = new MobileDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700471 mNetConfigs[netType].name);
Wink Savillec7a98342010-08-13 16:11:42 -0700472 mNetTrackers[netType].startMonitoring(context, mHandler);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700473 break;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800474 case ConnectivityManager.TYPE_DUMMY:
475 mNetTrackers[netType] = new DummyDataStateTracker(netType,
Wink Saville975c8482011-04-07 14:23:45 -0700476 mNetConfigs[netType].name);
Robert Greenwaltda3d5e62010-12-06 13:56:24 -0800477 mNetTrackers[netType].startMonitoring(context, mHandler);
478 break;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -0800479 case ConnectivityManager.TYPE_BLUETOOTH:
480 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
481 mNetTrackers[netType].startMonitoring(context, mHandler);
482 break;
Benoit Goby19970692010-12-22 14:29:40 -0800483 case ConnectivityManager.TYPE_ETHERNET:
484 mNetTrackers[netType] = EthernetDataTracker.getInstance();
485 mNetTrackers[netType].startMonitoring(context, mHandler);
486 break;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700487 default:
Wink Savilleed9c02b2010-12-03 12:01:38 -0800488 loge("Trying to create a DataStateTracker for an unknown radio type " +
Wink Saville975c8482011-04-07 14:23:45 -0700489 mNetConfigs[netType].radio);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700490 continue;
491 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700492 mCurrentLinkProperties[netType] = null;
Robert Greenwaltc96e6cc2011-07-15 11:16:45 -0700493 if (mNetConfigs[netType].isDefault()) mNetTrackers[netType].reconnect();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700494 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800495
Chia-chi Yehc9338302011-05-11 16:35:13 -0700496 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
497 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
498
499 mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700500 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700501 mTethering.getTetherableWifiRegexs().length != 0 ||
502 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700503 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800504
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700505 mVpn = new Vpn(mContext, new VpnCallback());
506
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700507 try {
508 nmService.registerObserver(mTethering);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700509 nmService.registerObserver(mVpn);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700510 } catch (RemoteException e) {
511 loge("Error registering observer :" + e);
512 }
513
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700514 if (DBG) {
515 mInetLog = new ArrayList();
516 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700517
518 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
519 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800520
521 loadGlobalProxy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 }
523
524 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700525 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 * @param preference the new preference
527 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700528 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700530
531 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 }
533
534 public int getNetworkPreference() {
535 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700536 int preference;
537 synchronized(this) {
538 preference = mNetworkPreference;
539 }
540 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 }
542
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700543 private void handleSetNetworkPreference(int preference) {
544 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700545 mNetConfigs[preference] != null &&
546 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700547 if (mNetworkPreference != preference) {
548 final ContentResolver cr = mContext.getContentResolver();
549 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
550 synchronized(this) {
551 mNetworkPreference = preference;
552 }
553 enforcePreference();
554 }
555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700557
Wink Saville628b0852011-08-04 15:01:58 -0700558 private int getConnectivityChangeDelay() {
559 final ContentResolver cr = mContext.getContentResolver();
560
561 /** Check system properties for the default value then use secure settings value, if any. */
562 int defaultDelay = SystemProperties.getInt(
563 "conn." + Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
564 Settings.Secure.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
565 return Settings.Secure.getInt(cr, Settings.Secure.CONNECTIVITY_CHANGE_DELAY,
566 defaultDelay);
567 }
568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 private int getPersistedNetworkPreference() {
570 final ContentResolver cr = mContext.getContentResolver();
571
572 final int networkPrefSetting = Settings.Secure
573 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
574 if (networkPrefSetting != -1) {
575 return networkPrefSetting;
576 }
577
578 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
579 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700582 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 * In this method, we only tear down a non-preferred network. Establishing
584 * a connection to the preferred network is taken care of when we handle
585 * the disconnect event from the non-preferred network
586 * (see {@link #handleDisconnect(NetworkInfo)}).
587 */
588 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700589 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 return;
591
Robert Greenwalt42acef32009-08-12 16:08:25 -0700592 if (!mNetTrackers[mNetworkPreference].isAvailable())
593 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594
Robert Greenwalt42acef32009-08-12 16:08:25 -0700595 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700596 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700597 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700598 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800599 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700600 " in enforcePreference");
601 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700602 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 }
604 }
605 }
606
607 private boolean teardown(NetworkStateTracker netTracker) {
608 if (netTracker.teardown()) {
609 netTracker.setTeardownRequested(true);
610 return true;
611 } else {
612 return false;
613 }
614 }
615
616 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700617 * Check if UID should be blocked from using the network represented by the
618 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700619 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700620 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
621 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700622
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700623 final boolean networkCostly;
624 final int uidRules;
625 synchronized (mRulesLock) {
626 networkCostly = mMeteredIfaces.contains(iface);
627 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700628 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700629
630 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
631 return true;
632 }
633
634 // no restrictive rules; network is visible
635 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700636 }
637
638 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700639 * Return a filtered {@link NetworkInfo}, potentially marked
640 * {@link DetailedState#BLOCKED} based on
641 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700642 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700643 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
644 NetworkInfo info = tracker.getNetworkInfo();
645 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700646 // network is blocked; clone and override state
647 info = new NetworkInfo(info);
648 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700649 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700650 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700651 }
652
653 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 * Return NetworkInfo for the active (i.e., connected) network interface.
655 * It is assumed that at most one network is active at a time. If more
656 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700657 * @return the info for the active network, or {@code null} if none is
658 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700660 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700662 enforceAccessPermission();
663 final int uid = Binder.getCallingUid();
664 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 }
666
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700667 @Override
668 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
669 enforceConnectivityInternalPermission();
670 return getNetworkInfo(mActiveDefaultNetwork, uid);
671 }
672
673 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 public NetworkInfo getNetworkInfo(int networkType) {
675 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700676 final int uid = Binder.getCallingUid();
677 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 }
679
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700680 private NetworkInfo getNetworkInfo(int networkType, int uid) {
681 NetworkInfo info = null;
682 if (isNetworkTypeValid(networkType)) {
683 final NetworkStateTracker tracker = mNetTrackers[networkType];
684 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700685 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700686 }
687 }
688 return info;
689 }
690
691 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 public NetworkInfo[] getAllNetworkInfo() {
693 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700694 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700695 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700696 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700697 for (NetworkStateTracker tracker : mNetTrackers) {
698 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700699 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700700 }
701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700703 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 }
705
Robert Greenwalt9b2886e2011-08-31 11:46:42 -0700706 @Override
707 public boolean isNetworkSupported(int networkType) {
708 enforceAccessPermission();
709 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
710 }
711
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700712 /**
713 * Return LinkProperties for the active (i.e., connected) default
714 * network interface. It is assumed that at most one default network
715 * is active at a time. If more than one is active, it is indeterminate
716 * which will be returned.
717 * @return the ip properties for the active network, or {@code null} if
718 * none is active
719 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700720 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700721 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700722 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700723 }
724
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700725 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700726 public LinkProperties getLinkProperties(int networkType) {
727 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700728 if (isNetworkTypeValid(networkType)) {
729 final NetworkStateTracker tracker = mNetTrackers[networkType];
730 if (tracker != null) {
731 return tracker.getLinkProperties();
732 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700733 }
734 return null;
735 }
736
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700737 @Override
738 public NetworkState[] getAllNetworkState() {
739 enforceAccessPermission();
740 final int uid = Binder.getCallingUid();
741 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700742 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700743 for (NetworkStateTracker tracker : mNetTrackers) {
744 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700745 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700746 result.add(new NetworkState(
747 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
748 }
749 }
750 }
751 return result.toArray(new NetworkState[result.size()]);
752 }
753
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700754 private NetworkState getNetworkStateUnchecked(int networkType) {
755 if (isNetworkTypeValid(networkType)) {
756 final NetworkStateTracker tracker = mNetTrackers[networkType];
757 if (tracker != null) {
758 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
759 tracker.getLinkCapabilities());
760 }
761 }
762 return null;
763 }
764
765 @Override
766 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
767 enforceAccessPermission();
768 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
769 if (state != null) {
770 try {
771 return mPolicyManager.getNetworkQuotaInfo(state);
772 } catch (RemoteException e) {
773 }
774 }
775 return null;
776 }
777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 public boolean setRadios(boolean turnOn) {
779 boolean result = true;
780 enforceChangePermission();
781 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700782 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 }
784 return result;
785 }
786
787 public boolean setRadio(int netType, boolean turnOn) {
788 enforceChangePermission();
789 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
790 return false;
791 }
792 NetworkStateTracker tracker = mNetTrackers[netType];
793 return tracker != null && tracker.setRadio(turnOn);
794 }
795
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700796 /**
797 * Used to notice when the calling process dies so we can self-expire
798 *
799 * Also used to know if the process has cleaned up after itself when
800 * our auto-expire timer goes off. The timer has a link to an object.
801 *
802 */
Robert Greenwalt42acef32009-08-12 16:08:25 -0700803 private class FeatureUser implements IBinder.DeathRecipient {
804 int mNetworkType;
805 String mFeature;
806 IBinder mBinder;
807 int mPid;
808 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -0800809 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700810
811 FeatureUser(int type, String feature, IBinder binder) {
812 super();
813 mNetworkType = type;
814 mFeature = feature;
815 mBinder = binder;
816 mPid = getCallingPid();
817 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -0800818 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700819
Robert Greenwalt42acef32009-08-12 16:08:25 -0700820 try {
821 mBinder.linkToDeath(this, 0);
822 } catch (RemoteException e) {
823 binderDied();
824 }
825 }
826
827 void unlinkDeathRecipient() {
828 mBinder.unlinkToDeath(this, 0);
829 }
830
831 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800832 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -0800833 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
834 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700835 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700836 }
837
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700838 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700839 if (VDBG) {
840 log("ConnectivityService FeatureUser expire(" +
841 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
842 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
843 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700844 stopUsingNetworkFeature(this, false);
845 }
Robert Greenwaltb9285352009-12-21 18:24:07 -0800846
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500847 public boolean isSameUser(FeatureUser u) {
848 if (u == null) return false;
849
850 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
851 }
852
853 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
854 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
855 TextUtils.equals(mFeature, feature)) {
856 return true;
857 }
858 return false;
859 }
860
Robert Greenwaltb9285352009-12-21 18:24:07 -0800861 public String toString() {
862 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
863 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
864 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700865 }
866
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700867 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -0700868 public int startUsingNetworkFeature(int networkType, String feature,
869 IBinder binder) {
Wink Savillec9acde92011-09-21 11:05:43 -0700870 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800871 log("startUsingNetworkFeature for net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 enforceChangePermission();
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700874 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700875 mNetConfigs[networkType] == null) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700876 return Phone.APN_REQUEST_FAILED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700878
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700879 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700880
repo syncaea743a2011-07-29 23:55:49 -0700881 // TODO - move this into individual networktrackers
882 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -0700883
884 if (mProtectedNetworks.contains(usedNetworkType)) {
885 enforceConnectivityInternalPermission();
886 }
887
Robert Greenwalt42acef32009-08-12 16:08:25 -0700888 NetworkStateTracker network = mNetTrackers[usedNetworkType];
889 if (network != null) {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800890 Integer currentPid = new Integer(getCallingPid());
Robert Greenwalt42acef32009-08-12 16:08:25 -0700891 if (usedNetworkType != networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700892 NetworkInfo ni = network.getNetworkInfo();
893
894 if (ni.isAvailable() == false) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800895 if (DBG) log("special network not available");
Robert Greenwalte32e8122010-12-29 14:35:21 -0800896 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
897 return Phone.APN_TYPE_NOT_AVAILABLE;
898 } else {
899 // else make the attempt anyway - probably giving REQUEST_STARTED below
900 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700901 }
902
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500903 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
904
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700905 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500906 boolean addToList = true;
907 if (restoreTimer < 0) {
908 // In case there is no timer is specified for the feature,
909 // make sure we don't add duplicate entry with the same request.
910 for (FeatureUser u : mFeatureUsers) {
911 if (u.isSameUser(f)) {
912 // Duplicate user is found. Do not add.
913 addToList = false;
914 break;
915 }
916 }
917 }
918
919 if (addToList) mFeatureUsers.add(f);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700920 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
921 // this gets used for per-pid dns when connected
922 mNetRequestersPids[usedNetworkType].add(currentPid);
923 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700924 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700925
Robert Greenwaltf2102f72011-05-03 19:02:44 -0700926 if (restoreTimer >= 0) {
927 mHandler.sendMessageDelayed(
928 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
929 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700930
Robert Greenwalta64bf832009-08-19 20:19:33 -0700931 if ((ni.isConnectedOrConnecting() == true) &&
932 !network.isTeardownRequested()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700933 if (ni.isConnected() == true) {
934 // add the pid-specific dns
repo sync89356962011-08-02 13:39:06 -0700935 handleDnsConfigurationChange(usedNetworkType);
Wink Savillec9acde92011-09-21 11:05:43 -0700936 if (VDBG) log("special network already active");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700937 return Phone.APN_ALREADY_ACTIVE;
938 }
Wink Savillec9acde92011-09-21 11:05:43 -0700939 if (VDBG) log("special network already connecting");
Robert Greenwalt42acef32009-08-12 16:08:25 -0700940 return Phone.APN_REQUEST_STARTED;
941 }
942
943 // check if the radio in play can make another contact
944 // assume if cannot for now
945
Wink Savillec9acde92011-09-21 11:05:43 -0700946 if (DBG) {
947 log("startUsingNetworkFeature reconnecting to " + networkType + ": " + feature);
948 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700949 network.reconnect();
950 return Phone.APN_REQUEST_STARTED;
951 } else {
Robert Greenwalt0be1e982010-12-15 13:26:33 -0800952 // need to remember this unsupported request so we respond appropriately on stop
953 synchronized(this) {
954 mFeatureUsers.add(f);
955 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
956 // this gets used for per-pid dns when connected
957 mNetRequestersPids[usedNetworkType].add(currentPid);
958 }
959 }
Robert Greenwalt02648a42010-05-18 10:52:51 -0700960 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700961 }
962 }
963 return Phone.APN_TYPE_NOT_AVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 }
965
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700966 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -0700968 enforceChangePermission();
969
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700970 int pid = getCallingPid();
971 int uid = getCallingUid();
972
973 FeatureUser u = null;
974 boolean found = false;
975
976 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500977 for (FeatureUser x : mFeatureUsers) {
978 if (x.isSameUser(pid, uid, networkType, feature)) {
979 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700980 found = true;
981 break;
982 }
983 }
984 }
985 if (found && u != null) {
986 // stop regardless of how many other time this proc had called start
987 return stopUsingNetworkFeature(u, true);
988 } else {
989 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -0700990 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700991 return 1;
992 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700993 }
994
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -0700995 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
996 int networkType = u.mNetworkType;
997 String feature = u.mFeature;
998 int pid = u.mPid;
999 int uid = u.mUid;
1000
1001 NetworkStateTracker tracker = null;
1002 boolean callTeardown = false; // used to carry our decision outside of sync block
1003
Wink Savillec9acde92011-09-21 11:05:43 -07001004 if (VDBG) {
1005 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001006 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001009 if (DBG) {
1010 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1011 ", net is invalid");
1012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 return -1;
1014 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001015
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001016 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1017 // sync block
1018 synchronized(this) {
1019 // check if this process still has an outstanding start request
1020 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001021 if (VDBG) {
1022 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1023 ", ignoring");
1024 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001025 return 1;
1026 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001027 u.unlinkDeathRecipient();
1028 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1029 // If we care about duplicate requests, check for that here.
1030 //
1031 // This is done to support the extension of a request - the app
1032 // can request we start the network feature again and renew the
1033 // auto-shutoff delay. Normal "stop" calls from the app though
1034 // do not pay attention to duplicate requests - in effect the
1035 // API does not refcount and a single stop will counter multiple starts.
1036 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001037 for (FeatureUser x : mFeatureUsers) {
1038 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001039 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001040 return 1;
1041 }
1042 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001043 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001044
repo syncaea743a2011-07-29 23:55:49 -07001045 // TODO - move to individual network trackers
1046 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1047
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001048 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001049 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001050 if (DBG) {
1051 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1052 " no known tracker for used net type " + usedNetworkType);
1053 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001054 return -1;
1055 }
1056 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001057 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001058 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -08001059 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001060 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001061 if (VDBG) {
1062 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1063 " others still using it");
1064 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001065 return 1;
1066 }
1067 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001068 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001069 if (DBG) {
1070 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1071 " not a known feature - dropping");
1072 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001073 }
1074 }
Wink Savillec9acde92011-09-21 11:05:43 -07001075
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001076 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001077 if (DBG) {
1078 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1079 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001080 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001081 return 1;
1082 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001083 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 }
1086
1087 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001088 * @deprecated use requestRouteToHostAddress instead
1089 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 * Ensure that a network route exists to deliver traffic to the specified
1091 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001092 * @param networkType the type of the network over which traffic to the
1093 * specified host is to be routed
1094 * @param hostAddress the IP address of the host to which the route is
1095 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 * @return {@code true} on success, {@code false} on failure
1097 */
1098 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001099 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1100
1101 if (inetAddress == null) {
1102 return false;
1103 }
1104
1105 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1106 }
1107
1108 /**
1109 * Ensure that a network route exists to deliver traffic to the specified
1110 * host via the specified network interface.
1111 * @param networkType the type of the network over which traffic to the
1112 * specified host is to be routed
1113 * @param hostAddress the IP address of the host to which the route is
1114 * desired
1115 * @return {@code true} on success, {@code false} on failure
1116 */
1117 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001119 if (mProtectedNetworks.contains(networkType)) {
1120 enforceConnectivityInternalPermission();
1121 }
1122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1124 return false;
1125 }
1126 NetworkStateTracker tracker = mNetTrackers[networkType];
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001127
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001128 if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
1129 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001130 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001131 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001132 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001133 }
1134 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001136 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001137 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001138 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001139 return addRouteToAddress(lp, addr);
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001140 } catch (UnknownHostException e) {}
1141 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001142 }
1143
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001144 private boolean addRoute(LinkProperties p, RouteInfo r) {
1145 return modifyRoute(p.getInterfaceName(), p, r, 0, true);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001146 }
1147
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001148 private boolean removeRoute(LinkProperties p, RouteInfo r) {
1149 return modifyRoute(p.getInterfaceName(), p, r, 0, false);
1150 }
1151
Robert Greenwaltad55d352011-07-22 11:55:33 -07001152 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1153 return modifyRouteToAddress(lp, addr, true);
1154 }
1155
1156 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1157 return modifyRouteToAddress(lp, addr, false);
1158 }
1159
1160 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd) {
1161 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1162 if (bestRoute == null) {
1163 bestRoute = RouteInfo.makeHostRoute(addr);
1164 } else {
1165 if (bestRoute.getGateway().equals(addr)) {
1166 // if there is no better route, add the implied hostroute for our gateway
1167 bestRoute = RouteInfo.makeHostRoute(addr);
1168 } else {
1169 // if we will connect to this through another route, add a direct route
1170 // to it's gateway
1171 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1172 }
1173 }
1174 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd);
1175 }
1176
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001177 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
1178 boolean doAdd) {
1179 if ((ifaceName == null) || (lp == null) || (r == null)) return false;
1180
1181 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1182 loge("Error adding route - too much recursion");
1183 return false;
1184 }
1185
1186 if (r.isHostRoute() == false) {
1187 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1188 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001189 if (bestRoute.getGateway().equals(r.getGateway())) {
1190 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001191 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-07-15 09:45:08 -07001192 } else {
1193 // if we will connect to our gateway through another route, add a direct
1194 // route to it's gateway
1195 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001196 }
Robert Greenwalt476f5522011-07-15 09:45:08 -07001197 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001198 }
1199 }
1200 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001201 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001202 mAddedRoutes.add(r);
1203 try {
1204 mNetd.addRoute(ifaceName, r);
1205 } catch (Exception e) {
1206 // never crash - catch them all
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001207 if (VDBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001208 return false;
1209 }
1210 } else {
1211 // if we remove this one and there are no more like it, then refcount==0 and
1212 // we can remove it from the table
1213 mAddedRoutes.remove(r);
1214 if (mAddedRoutes.contains(r) == false) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001215 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001216 try {
1217 mNetd.removeRoute(ifaceName, r);
1218 } catch (Exception e) {
1219 // never crash - catch them all
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001220 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001221 return false;
1222 }
1223 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001224 if (VDBG) log("not removing " + r + " as it's still in use");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001225 }
1226 }
1227 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 }
1229
1230 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001231 * @see ConnectivityManager#getMobileDataEnabled()
1232 */
1233 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001234 // TODO: This detail should probably be in DataConnectionTracker's
1235 // which is where we store the value and maybe make this
1236 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001237 enforceAccessPermission();
1238 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1239 Settings.Secure.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001240 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001241 return retVal;
1242 }
1243
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001244 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001245 enforceConnectivityInternalPermission();
1246
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001247 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1248 (met ? ENABLED : DISABLED), networkType));
1249 }
1250
1251 private void handleSetDependencyMet(int networkType, boolean met) {
1252 if (mNetTrackers[networkType] != null) {
1253 if (DBG) {
1254 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1255 }
1256 mNetTrackers[networkType].setDependencyMet(met);
1257 }
1258 }
1259
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001260 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1261 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001262 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001263 // only someone like NPMS should only be calling us
Jeff Sharkey1a303952011-06-16 13:04:20 -07001264 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001265
1266 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001267 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001268 }
1269
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001270 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001271 // skip update when we've already applied rules
1272 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1273 if (oldRules == uidRules) return;
1274
1275 mUidRules.put(uid, uidRules);
1276 }
1277
1278 // TODO: dispatch into NMS to push rules towards kernel module
1279 // TODO: notify UID when it has requested targeted updates
1280 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001281
1282 @Override
1283 public void onMeteredIfacesChanged(String[] meteredIfaces) {
1284 // only someone like NPMS should only be calling us
1285 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1286
1287 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001288 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001289 }
1290
1291 synchronized (mRulesLock) {
1292 mMeteredIfaces.clear();
1293 for (String iface : meteredIfaces) {
1294 mMeteredIfaces.add(iface);
1295 }
1296 }
1297 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001298 };
1299
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001300 /**
1301 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1302 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001303 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001304 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001305 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001306
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001307 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001308 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001309 }
1310
1311 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001312 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001313 if (VDBG) {
1314 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001315 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001316 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1317 }
1318 }
1319
1320 @Override
1321 public void setPolicyDataEnable(int networkType, boolean enabled) {
1322 // only someone like NPMS should only be calling us
1323 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1324
1325 mHandler.sendMessage(mHandler.obtainMessage(
1326 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1327 }
1328
1329 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1330 if (isNetworkTypeValid(networkType)) {
1331 final NetworkStateTracker tracker = mNetTrackers[networkType];
1332 if (tracker != null) {
1333 tracker.setPolicyDataEnable(enabled);
1334 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001335 }
1336 }
1337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001339 mContext.enforceCallingOrSelfPermission(
1340 android.Manifest.permission.ACCESS_NETWORK_STATE,
1341 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 }
1343
1344 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001345 mContext.enforceCallingOrSelfPermission(
1346 android.Manifest.permission.CHANGE_NETWORK_STATE,
1347 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 }
1349
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001350 // TODO Make this a special check when it goes public
1351 private void enforceTetherChangePermission() {
1352 mContext.enforceCallingOrSelfPermission(
1353 android.Manifest.permission.CHANGE_NETWORK_STATE,
1354 "ConnectivityService");
1355 }
1356
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001357 private void enforceTetherAccessPermission() {
1358 mContext.enforceCallingOrSelfPermission(
1359 android.Manifest.permission.ACCESS_NETWORK_STATE,
1360 "ConnectivityService");
1361 }
1362
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001363 private void enforceConnectivityInternalPermission() {
1364 mContext.enforceCallingOrSelfPermission(
1365 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1366 "ConnectivityService");
1367 }
1368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001370 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1371 * network, we ignore it. If it is for the active network, we send out a
1372 * broadcast. But first, we check whether it might be possible to connect
1373 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 * @param info the {@code NetworkInfo} for the network
1375 */
1376 private void handleDisconnect(NetworkInfo info) {
1377
Robert Greenwalt42acef32009-08-12 16:08:25 -07001378 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379
Robert Greenwalt42acef32009-08-12 16:08:25 -07001380 mNetTrackers[prevNetType].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 /*
1382 * If the disconnected network is not the active one, then don't report
1383 * this as a loss of connectivity. What probably happened is that we're
1384 * getting the disconnect for a network that we explicitly disabled
1385 * in accordance with network preference policies.
1386 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001387 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001388 List pids = mNetRequestersPids[prevNetType];
1389 for (int i = 0; i<pids.size(); i++) {
1390 Integer pid = (Integer)pids.get(i);
1391 // will remove them because the net's no longer connected
1392 // need to do this now as only now do we know the pids and
1393 // can properly null things that are no longer referenced.
1394 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 }
1397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1399 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1400 if (info.isFailover()) {
1401 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1402 info.setFailover(false);
1403 }
1404 if (info.getReason() != null) {
1405 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1406 }
1407 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001408 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1409 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001411
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001412 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001413 tryFailover(prevNetType);
1414 if (mActiveDefaultNetwork != -1) {
1415 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001416 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1417 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001418 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001419 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1420 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001421 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001422 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001423
1424 // Reset interface if no other connections are using the same interface
1425 boolean doReset = true;
1426 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1427 if (linkProperties != null) {
1428 String oldIface = linkProperties.getInterfaceName();
1429 if (TextUtils.isEmpty(oldIface) == false) {
1430 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1431 if (networkStateTracker == null) continue;
1432 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1433 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1434 LinkProperties l = networkStateTracker.getLinkProperties();
1435 if (l == null) continue;
1436 if (oldIface.equals(l.getInterfaceName())) {
1437 doReset = false;
1438 break;
1439 }
1440 }
1441 }
1442 }
1443 }
1444
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001445 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001446 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001447
Jeff Sharkey961e3042011-08-29 16:02:57 -07001448 final Intent immediateIntent = new Intent(intent);
1449 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1450 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001451 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001452 /*
1453 * If the failover network is already connected, then immediately send
1454 * out a followup broadcast indicating successful failover
1455 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001456 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001457 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1458 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001459 }
1460 }
1461
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001462 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001463 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001464 * If this is a default network, check if other defaults are available.
1465 * Try to reconnect on all available and let them hash it out when
1466 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001467 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001468 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001469 if (mActiveDefaultNetwork == prevNetType) {
1470 mActiveDefaultNetwork = -1;
1471 }
1472
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001473 // don't signal a reconnect for anything lower or equal priority than our
1474 // current connected default
1475 // TODO - don't filter by priority now - nice optimization but risky
1476// int currentPriority = -1;
1477// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001478// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001479// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001480 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001481 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001482 if (mNetConfigs[checkType] == null) continue;
1483 if (!mNetConfigs[checkType].isDefault()) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001484
1485// Enabling the isAvailable() optimization caused mobile to not get
1486// selected if it was in the middle of error handling. Specifically
1487// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1488// would not be available and we wouldn't get connected to anything.
1489// So removing the isAvailable() optimization below for now. TODO: This
1490// optimization should work and we need to investigate why it doesn't work.
1491// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1492// complete before it is really complete.
1493// if (!mNetTrackers[checkType].isAvailable()) continue;
1494
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001495// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001496
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001497 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1498 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1499 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1500 checkInfo.setFailover(true);
1501 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001502 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001503 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
1507
1508 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001509 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1510 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001511 }
1512
Wink Saville628b0852011-08-04 15:01:58 -07001513 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001514 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1515 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001516 }
1517
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001518 private void sendInetConditionBroadcast(NetworkInfo info) {
1519 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1520 }
1521
Wink Saville628b0852011-08-04 15:01:58 -07001522 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001523 Intent intent = new Intent(bcastType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1525 if (info.isFailover()) {
1526 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1527 info.setFailover(false);
1528 }
1529 if (info.getReason() != null) {
1530 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1531 }
1532 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001533 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1534 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001536 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001537 return intent;
1538 }
1539
1540 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1541 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1542 }
1543
1544 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1545 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547
1548 /**
1549 * Called when an attempt to fail over to another network has failed.
1550 * @param info the {@link NetworkInfo} for the failed network
1551 */
1552 private void handleConnectionFailure(NetworkInfo info) {
1553 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554
Robert Greenwalt42acef32009-08-12 16:08:25 -07001555 String reason = info.getReason();
1556 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001557
Robert Greenwalt572172b2010-10-08 16:35:52 -07001558 String reasonText;
1559 if (reason == null) {
1560 reasonText = ".";
1561 } else {
1562 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001564 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001565
1566 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1567 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1568 if (getActiveNetworkInfo() == null) {
1569 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1570 }
1571 if (reason != null) {
1572 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1573 }
1574 if (extraInfo != null) {
1575 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1576 }
1577 if (info.isFailover()) {
1578 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1579 info.setFailover(false);
1580 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001581
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001582 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001583 tryFailover(info.getType());
1584 if (mActiveDefaultNetwork != -1) {
1585 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001586 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1587 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001588 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001589 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1590 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001591 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001592
Robert Greenwalt029be812010-09-20 18:01:43 -07001593 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07001594
1595 final Intent immediateIntent = new Intent(intent);
1596 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1597 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001598 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001599 /*
1600 * If the failover network is already connected, then immediately send
1601 * out a followup broadcast indicating successful failover
1602 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001603 if (mActiveDefaultNetwork != -1) {
1604 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001605 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001606 }
1607
1608 private void sendStickyBroadcast(Intent intent) {
1609 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001610 if (!mSystemReady) {
1611 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001612 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001613 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07001614 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001615 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001616 }
1617
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001618 mContext.sendStickyBroadcast(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001619 }
1620 }
1621
Wink Saville628b0852011-08-04 15:01:58 -07001622 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1623 if (delayMs <= 0) {
1624 sendStickyBroadcast(intent);
1625 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001626 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001627 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1628 + intent.getAction());
1629 }
Wink Saville628b0852011-08-04 15:01:58 -07001630 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1631 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1632 }
1633 }
1634
Mike Lockwood0f79b542009-08-14 14:18:49 -04001635 void systemReady() {
1636 synchronized(this) {
1637 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001638 if (mInitialBroadcast != null) {
1639 mContext.sendStickyBroadcast(mInitialBroadcast);
1640 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001641 }
1642 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001643 // load the global proxy at startup
1644 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 }
1646
1647 private void handleConnect(NetworkInfo info) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001648 int type = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649
1650 // snapshot isFailover, because sendConnectedBroadcast() resets it
1651 boolean isFailover = info.isFailover();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001652 NetworkStateTracker thisNet = mNetTrackers[type];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653
Robert Greenwalt42acef32009-08-12 16:08:25 -07001654 // if this is a default net and other default is running
1655 // kill the one not preferred
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001656 if (mNetConfigs[type].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001657 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1658 if ((type != mNetworkPreference &&
Wink Saville975c8482011-04-07 14:23:45 -07001659 mNetConfigs[mActiveDefaultNetwork].priority >
1660 mNetConfigs[type].priority) ||
Robert Greenwalt42acef32009-08-12 16:08:25 -07001661 mNetworkPreference == mActiveDefaultNetwork) {
1662 // don't accept this one
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001663 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001664 log("Not broadcasting CONNECT_ACTION " +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001665 "to torn down network " + info.getTypeName());
Wink Savilleed9c02b2010-12-03 12:01:38 -08001666 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001667 teardown(thisNet);
1668 return;
1669 } else {
1670 // tear down the other
1671 NetworkStateTracker otherNet =
1672 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08001673 if (DBG) {
1674 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07001675 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08001676 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001677 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001678 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07001679 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001680 return;
1681 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001682 }
1683 }
1684 synchronized (ConnectivityService.this) {
1685 // have a new default network, release the transition wakelock in a second
1686 // if it's held. The second pause is to allow apps to reconnect over the
1687 // new network
1688 if (mNetTransitionWakeLock.isHeld()) {
1689 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07001690 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001691 mNetTransitionWakeLockSerialNumber, 0),
1692 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001693 }
1694 }
1695 mActiveDefaultNetwork = type;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001696 // this will cause us to come up initially as unconnected and switching
1697 // to connected after our normal pause unless somebody reports us as reall
1698 // disconnected
1699 mDefaultInetConditionPublished = 0;
1700 mDefaultConnectionSequence++;
1701 mInetConditionChangeInFlight = false;
1702 // Don't do this - if we never sign in stay, grey
1703 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001706 updateNetworkSettings(thisNet);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001707 handleConnectivityChange(type, false);
Wink Saville628b0852011-08-04 15:01:58 -07001708 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 }
1710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001712 * After a change in the connectivity state of a network. We're mainly
1713 * concerned with making sure that the list of DNS servers is set up
1714 * according to which networks are connected, and ensuring that the
1715 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07001717 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07001718 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
1719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07001721 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001722 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001724 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001725
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001726 LinkProperties curLp = mCurrentLinkProperties[netType];
1727 LinkProperties newLp = null;
1728
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001729 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001730 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07001731 if (VDBG) {
1732 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1733 " doReset=" + doReset + " resetMask=" + resetMask +
1734 "\n curLp=" + curLp +
1735 "\n newLp=" + newLp);
1736 }
1737
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001738 if (curLp != null) {
1739 if (curLp.isIdenticalInterfaceName(newLp)) {
1740 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
1741 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
1742 for (LinkAddress linkAddr : car.removed) {
1743 if (linkAddr.getAddress() instanceof Inet4Address) {
1744 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
1745 }
1746 if (linkAddr.getAddress() instanceof Inet6Address) {
1747 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
1748 }
Wink Savillee8222252011-07-13 13:44:13 -07001749 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001750 if (DBG) {
1751 log("handleConnectivityChange: addresses changed" +
1752 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
1753 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07001754 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001755 } else {
1756 if (DBG) {
1757 log("handleConnectivityChange: address are the same reset per doReset" +
1758 " linkProperty[" + netType + "]:" +
1759 " resetMask=" + resetMask);
1760 }
Wink Savillee8222252011-07-13 13:44:13 -07001761 }
1762 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001763 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001764 if (DBG) {
1765 log("handleConnectivityChange: interface not not equivalent reset both" +
1766 " linkProperty[" + netType + "]:" +
1767 " resetMask=" + resetMask);
1768 }
Wink Savillee8222252011-07-13 13:44:13 -07001769 }
Wink Savillee8222252011-07-13 13:44:13 -07001770 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001771 if (mNetConfigs[netType].isDefault()) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07001772 handleApplyDefaultProxy(netType);
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07001773 }
1774 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001775 if (VDBG) {
1776 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
1777 " doReset=" + doReset + " resetMask=" + resetMask +
1778 "\n curLp=" + curLp +
1779 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07001780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001781 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001782 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07001783 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07001784
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001785 if (resetMask != 0 || resetDns) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07001786 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
1787 if (linkProperties != null) {
1788 String iface = linkProperties.getInterfaceName();
1789 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001790 if (resetMask != 0) {
Robert Greenwaltf125a092011-08-15 12:31:55 -07001791 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
1792 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07001793
1794 // Tell VPN the interface is down. It is a temporary
1795 // but effective fix to make VPN aware of the change.
1796 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
1797 mVpn.interfaceStatusChanged(iface, false);
1798 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07001799 }
1800 if (resetDns) {
Wink Savillec9acde92011-09-21 11:05:43 -07001801 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwaltf125a092011-08-15 12:31:55 -07001802 try {
1803 mNetd.flushInterfaceDnsCache(iface);
1804 } catch (Exception e) {
1805 // never crash - catch them all
Wink Savillec9acde92011-09-21 11:05:43 -07001806 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwaltf125a092011-08-15 12:31:55 -07001807 }
1808 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07001809 }
1810 }
1811 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05001812
1813 // TODO: Temporary notifying upstread change to Tethering.
1814 // @see bug/4455071
1815 /** Notify TetheringService if interface name has been changed. */
1816 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1817 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1818 if (isTetheringSupported()) {
1819 mTethering.handleTetherIfaceChange();
1820 }
1821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
1823
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001824 /**
1825 * Add and remove routes using the old properties (null if not previously connected),
1826 * new properties (null if becoming disconnected). May even be double null, which
1827 * is a noop.
1828 * Uses isLinkDefault to determine if default routes should be set or conversely if
1829 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07001830 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001831 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07001832 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
1833 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001834 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07001835 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
1836 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001837 if (curLp != null) {
1838 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07001839 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001840 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001841 } else if (newLp != null) {
1842 routeDiff.added = newLp.getRoutes();
1843 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07001844 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001845
Robert Greenwaltf125a092011-08-15 12:31:55 -07001846 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
1847
Robert Greenwaltad55d352011-07-22 11:55:33 -07001848 for (RouteInfo r : routeDiff.removed) {
1849 if (isLinkDefault || ! r.isDefaultRoute()) {
1850 removeRoute(curLp, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001851 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07001852 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001853
Robert Greenwaltad55d352011-07-22 11:55:33 -07001854 for (RouteInfo r : routeDiff.added) {
1855 if (isLinkDefault || ! r.isDefaultRoute()) {
1856 addRoute(newLp, r);
Robert Greenwalte6b24292011-08-09 16:52:58 -07001857 } else {
1858 // many radios add a default route even when we don't want one.
1859 // remove the default route unless somebody else has asked for it
1860 String ifaceName = newLp.getInterfaceName();
1861 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07001862 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte6b24292011-08-09 16:52:58 -07001863 try {
1864 mNetd.removeRoute(ifaceName, r);
1865 } catch (Exception e) {
1866 // never crash - catch them all
Wink Savillec9acde92011-09-21 11:05:43 -07001867 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte6b24292011-08-09 16:52:58 -07001868 }
1869 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001870 }
1871 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001872
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001873 if (!isLinkDefault) {
1874 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07001875 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07001876 // routes changed - remove all old dns entries and add new
1877 if (curLp != null) {
1878 for (InetAddress oldDns : curLp.getDnses()) {
1879 removeRouteToAddress(curLp, oldDns);
1880 }
1881 }
1882 if (newLp != null) {
1883 for (InetAddress newDns : newLp.getDnses()) {
1884 addRouteToAddress(newLp, newDns);
1885 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07001886 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07001887 } else {
1888 // no change in routes, check for change in dns themselves
1889 for (InetAddress oldDns : dnsDiff.removed) {
1890 removeRouteToAddress(curLp, oldDns);
1891 }
1892 for (InetAddress newDns : dnsDiff.added) {
1893 addRouteToAddress(newLp, newDns);
1894 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001895 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001896 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07001897 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001898 }
1899
1900
Irfan Sheriffd649c122010-06-09 15:39:36 -07001901 /**
1902 * Reads the network specific TCP buffer sizes from SystemProperties
1903 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1904 * wide use
1905 */
1906 public void updateNetworkSettings(NetworkStateTracker nt) {
1907 String key = nt.getTcpBufferSizesPropName();
1908 String bufferSizes = SystemProperties.get(key);
1909
1910 if (bufferSizes.length() == 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001911 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07001912
1913 // Setting to default values so we won't be stuck to previous values
1914 key = "net.tcp.buffersize.default";
1915 bufferSizes = SystemProperties.get(key);
1916 }
1917
1918 // Set values in kernel
1919 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001920 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001921 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07001922 + "] which comes from [" + key + "]");
1923 }
1924 setBufferSize(bufferSizes);
1925 }
1926 }
1927
1928 /**
1929 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1930 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1931 *
1932 * @param bufferSizes in the format of "readMin, readInitial, readMax,
1933 * writeMin, writeInitial, writeMax"
1934 */
1935 private void setBufferSize(String bufferSizes) {
1936 try {
1937 String[] values = bufferSizes.split(",");
1938
1939 if (values.length == 6) {
1940 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04001941 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1942 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1943 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1944 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1945 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1946 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001947 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001948 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001949 }
1950 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001951 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001952 }
1953 }
1954
Robert Greenwalt42acef32009-08-12 16:08:25 -07001955 /**
1956 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1957 * on the highest priority active net which this process requested.
1958 * If there aren't any, clear it out
1959 */
1960 private void reassessPidDns(int myPid, boolean doBump)
1961 {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001962 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001963 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001964 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001965 continue;
1966 }
1967 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001968 if (nt.getNetworkInfo().isConnected() &&
1969 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07001970 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001971 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001972 List pids = mNetRequestersPids[i];
1973 for (int j=0; j<pids.size(); j++) {
1974 Integer pid = (Integer)pids.get(j);
1975 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001976 Collection<InetAddress> dnses = p.getDnses();
1977 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001978 if (doBump) {
1979 bumpDns();
1980 }
1981 return;
1982 }
1983 }
1984 }
1985 }
1986 // nothing found - delete
1987 for (int i = 1; ; i++) {
1988 String prop = "net.dns" + i + "." + myPid;
1989 if (SystemProperties.get(prop).length() == 0) {
1990 if (doBump) {
1991 bumpDns();
1992 }
1993 return;
1994 }
1995 SystemProperties.set(prop, "");
1996 }
1997 }
1998
Robert Greenwalt10398722010-12-17 15:20:36 -08001999 // return true if results in a change
2000 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002001 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08002002 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002003 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08002004 String dnsString = dns.getHostAddress();
2005 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2006 changed = true;
2007 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
2008 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002009 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002010 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002011 }
2012
2013 private void bumpDns() {
2014 /*
2015 * Bump the property that tells the name resolver library to reread
2016 * the DNS server list from the properties.
2017 */
2018 String propVal = SystemProperties.get("net.dnschange");
2019 int n = 0;
2020 if (propVal.length() != 0) {
2021 try {
2022 n = Integer.parseInt(propVal);
2023 } catch (NumberFormatException e) {}
2024 }
2025 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07002026 /*
2027 * Tell the VMs to toss their DNS caches
2028 */
2029 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2030 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002031 /*
2032 * Connectivity events can happen before boot has completed ...
2033 */
2034 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt03595d02010-11-02 14:08:23 -07002035 mContext.sendBroadcast(intent);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002036 }
2037
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002038 // Caller must grab mDnsLock.
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002039 private boolean updateDns(String network, String iface,
2040 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002041 boolean changed = false;
2042 int last = 0;
2043 if (dnses.size() == 0 && mDefaultDns != null) {
2044 ++last;
2045 String value = mDefaultDns.getHostAddress();
2046 if (!value.equals(SystemProperties.get("net.dns1"))) {
2047 if (DBG) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002048 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002049 }
2050 changed = true;
2051 SystemProperties.set("net.dns1", value);
2052 }
2053 } else {
2054 for (InetAddress dns : dnses) {
2055 ++last;
2056 String key = "net.dns" + last;
2057 String value = dns.getHostAddress();
2058 if (!changed && value.equals(SystemProperties.get(key))) {
2059 continue;
2060 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002061 if (VDBG) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002062 log("adding dns " + value + " for " + network);
2063 }
2064 changed = true;
2065 SystemProperties.set(key, value);
2066 }
2067 }
2068 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2069 String key = "net.dns" + i;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002070 if (VDBG) log("erasing " + key);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002071 changed = true;
2072 SystemProperties.set(key, "");
2073 }
2074 mNumDnsEntries = last;
2075
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002076 if (changed) {
2077 try {
2078 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
2079 mNetd.setDefaultInterfaceForDns(iface);
2080 } catch (Exception e) {
Wink Savillec9acde92011-09-21 11:05:43 -07002081 if (VDBG) loge("exception setting default dns interface: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002082 }
2083 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002084 if (!domains.equals(SystemProperties.get("net.dns.search"))) {
2085 SystemProperties.set("net.dns.search", domains);
2086 changed = true;
2087 }
2088 return changed;
2089 }
2090
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002091 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002092 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002093 NetworkStateTracker nt = mNetTrackers[netType];
2094 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002095 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002096 if (p == null) return;
2097 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08002098 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002099 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002100 String network = nt.getNetworkInfo().getTypeName();
2101 synchronized (mDnsLock) {
2102 if (!mDnsOverridden) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002103 changed = updateDns(network, p.getInterfaceName(), dnses, "");
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002104 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002105 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002106 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002107 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002108 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002109 NetworkUtils.makeStrings(dnses));
2110 } catch (Exception e) {
Wink Savillec9acde92011-09-21 11:05:43 -07002111 if (VDBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002112 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002113 // set per-pid dns for attached secondary nets
2114 List pids = mNetRequestersPids[netType];
2115 for (int y=0; y< pids.size(); y++) {
2116 Integer pid = (Integer)pids.get(y);
Robert Greenwalt10398722010-12-17 15:20:36 -08002117 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 }
2119 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002120 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002122 }
2123
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002124 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002125 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2126 NETWORK_RESTORE_DELAY_PROP_NAME);
2127 if(restoreDefaultNetworkDelayStr != null &&
2128 restoreDefaultNetworkDelayStr.length() != 0) {
2129 try {
2130 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2131 } catch (NumberFormatException e) {
2132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002134 // if the system property isn't set, use the value for the apn type
2135 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2136
2137 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2138 (mNetConfigs[networkType] != null)) {
2139 ret = mNetConfigs[networkType].restoreTime;
2140 }
2141 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 }
2143
2144 @Override
2145 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002146 if (mContext.checkCallingOrSelfPermission(
2147 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002149 pw.println("Permission Denial: can't dump ConnectivityService " +
2150 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2151 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 return;
2153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 pw.println();
2155 for (NetworkStateTracker nst : mNetTrackers) {
Robert Greenwaltb9285352009-12-21 18:24:07 -08002156 if (nst != null) {
2157 if (nst.getNetworkInfo().isConnected()) {
2158 pw.println("Active network: " + nst.getNetworkInfo().
2159 getTypeName());
2160 }
2161 pw.println(nst.getNetworkInfo());
2162 pw.println(nst);
2163 pw.println();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002165 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002166
2167 pw.println("Network Requester Pids:");
2168 for (int net : mPriorityList) {
2169 String pidString = net + ": ";
2170 for (Object pid : mNetRequestersPids[net]) {
2171 pidString = pidString + pid.toString() + ", ";
2172 }
2173 pw.println(pidString);
2174 }
2175 pw.println();
2176
2177 pw.println("FeatureUsers:");
2178 for (Object requester : mFeatureUsers) {
2179 pw.println(requester.toString());
2180 }
2181 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002182
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002183 synchronized (this) {
2184 pw.println("NetworkTranstionWakeLock is currently " +
2185 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2186 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2187 }
2188 pw.println();
2189
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002190 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002191
2192 if (mInetLog != null) {
2193 pw.println();
2194 pw.println("Inet condition reports:");
2195 for(int i = 0; i < mInetLog.size(); i++) {
2196 pw.println(mInetLog.get(i));
2197 }
2198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 }
2200
Robert Greenwalt42acef32009-08-12 16:08:25 -07002201 // must be stateless - things change under us.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 private class MyHandler extends Handler {
Wink Savillebb08caf2010-09-02 19:23:52 -07002203 public MyHandler(Looper looper) {
2204 super(looper);
2205 }
2206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 @Override
2208 public void handleMessage(Message msg) {
2209 NetworkInfo info;
2210 switch (msg.what) {
2211 case NetworkStateTracker.EVENT_STATE_CHANGED:
2212 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002213 int type = info.getType();
2214 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002215
Wink Savillec9acde92011-09-21 11:05:43 -07002216 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2217 (state == NetworkInfo.State.DISCONNECTED)) {
2218 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002219 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002220 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002222
2223 // Connectivity state changed:
2224 // [31-13] Reserved for future use
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002225 // [12-9] Network subtype (for mobile network, as defined
2226 // by TelephonyManager)
2227 // [8-3] Detailed state ordinal (as defined by
2228 // NetworkInfo.DetailedState)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229 // [2-0] Network type (as defined by ConnectivityManager)
2230 int eventLogParam = (info.getType() & 0x7) |
2231 ((info.getDetailedState().ordinal() & 0x3f) << 3) |
2232 (info.getSubtype() << 9);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002233 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002234 eventLogParam);
2235
2236 if (info.getDetailedState() ==
2237 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002238 handleConnectionFailure(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002239 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002241 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002243 // the logic here is, handle SUSPENDED the same as
2244 // DISCONNECTED. The only difference being we are
2245 // broadcasting an intent with NetworkInfo that's
2246 // suspended. This allows the applications an
2247 // opportunity to handle DISCONNECTED and SUSPENDED
2248 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002250 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 handleConnect(info);
2252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002253 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002255 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002256 // TODO: Temporary allowing network configuration
2257 // change not resetting sockets.
2258 // @see bug/4455071
2259 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 break;
Robert Greenwaltf3331232010-09-24 14:32:21 -07002261 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002262 String causedBy = null;
2263 synchronized (ConnectivityService.this) {
2264 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2265 mNetTransitionWakeLock.isHeld()) {
2266 mNetTransitionWakeLock.release();
2267 causedBy = mNetTransitionWakeLockCausedBy;
2268 }
2269 }
2270 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002271 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002272 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002273 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002274 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002275 FeatureUser u = (FeatureUser)msg.obj;
2276 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002277 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002278 case EVENT_INET_CONDITION_CHANGE:
2279 {
2280 int netType = msg.arg1;
2281 int condition = msg.arg2;
2282 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002283 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002284 }
2285 case EVENT_INET_CONDITION_HOLD_END:
2286 {
2287 int netType = msg.arg1;
2288 int sequence = msg.arg2;
2289 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002290 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002291 }
2292 case EVENT_SET_NETWORK_PREFERENCE:
2293 {
2294 int preference = msg.arg1;
2295 handleSetNetworkPreference(preference);
2296 break;
2297 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002298 case EVENT_SET_MOBILE_DATA:
2299 {
2300 boolean enabled = (msg.arg1 == ENABLED);
2301 handleSetMobileData(enabled);
2302 break;
2303 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002304 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2305 {
2306 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002307 break;
2308 }
2309 case EVENT_SET_DEPENDENCY_MET:
2310 {
2311 boolean met = (msg.arg1 == ENABLED);
2312 handleSetDependencyMet(msg.arg2, met);
2313 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002314 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002315 case EVENT_RESTORE_DNS:
2316 {
2317 if (mActiveDefaultNetwork != -1) {
2318 handleDnsConfigurationChange(mActiveDefaultNetwork);
2319 }
2320 break;
2321 }
Wink Saville628b0852011-08-04 15:01:58 -07002322 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2323 {
2324 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002325 sendStickyBroadcast(intent);
2326 break;
2327 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002328 case EVENT_SET_POLICY_DATA_ENABLE: {
2329 final int networkType = msg.arg1;
2330 final boolean enabled = msg.arg2 == ENABLED;
2331 handleSetPolicyDataEnable(networkType, enabled);
2332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 }
2334 }
2335 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002336
2337 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002338 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002339 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002340
2341 if (isTetheringSupported()) {
2342 return mTethering.tether(iface);
2343 } else {
2344 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2345 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002346 }
2347
2348 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002349 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002350 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002351
2352 if (isTetheringSupported()) {
2353 return mTethering.untether(iface);
2354 } else {
2355 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2356 }
2357 }
2358
2359 // javadoc from interface
2360 public int getLastTetherError(String iface) {
2361 enforceTetherAccessPermission();
2362
2363 if (isTetheringSupported()) {
2364 return mTethering.getLastTetherError(iface);
2365 } else {
2366 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2367 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002368 }
2369
2370 // TODO - proper iface API for selection by property, inspection, etc
2371 public String[] getTetherableUsbRegexs() {
2372 enforceTetherAccessPermission();
2373 if (isTetheringSupported()) {
2374 return mTethering.getTetherableUsbRegexs();
2375 } else {
2376 return new String[0];
2377 }
2378 }
2379
2380 public String[] getTetherableWifiRegexs() {
2381 enforceTetherAccessPermission();
2382 if (isTetheringSupported()) {
2383 return mTethering.getTetherableWifiRegexs();
2384 } else {
2385 return new String[0];
2386 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002387 }
2388
Danica Chang6fdd0c62010-08-11 14:54:43 -07002389 public String[] getTetherableBluetoothRegexs() {
2390 enforceTetherAccessPermission();
2391 if (isTetheringSupported()) {
2392 return mTethering.getTetherableBluetoothRegexs();
2393 } else {
2394 return new String[0];
2395 }
2396 }
2397
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002398 public int setUsbTethering(boolean enable) {
2399 enforceTetherAccessPermission();
2400 if (isTetheringSupported()) {
2401 return mTethering.setUsbTethering(enable);
2402 } else {
2403 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2404 }
2405 }
2406
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002407 // TODO - move iface listing, queries, etc to new module
2408 // javadoc from interface
2409 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002410 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002411 return mTethering.getTetherableIfaces();
2412 }
2413
2414 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002415 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002416 return mTethering.getTetheredIfaces();
2417 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002418
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07002419 @Override
2420 public String[] getTetheredIfacePairs() {
2421 enforceTetherAccessPermission();
2422 return mTethering.getTetheredIfacePairs();
2423 }
2424
Robert Greenwalt5a735062010-03-02 17:25:02 -08002425 public String[] getTetheringErroredIfaces() {
2426 enforceTetherAccessPermission();
2427 return mTethering.getErroredIfaces();
2428 }
2429
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002430 // if ro.tether.denied = true we default to no tethering
2431 // gservices could set the secure setting to 1 though to enable it on a build where it
2432 // had previously been turned off.
2433 public boolean isTetheringSupported() {
2434 enforceTetherAccessPermission();
2435 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002436 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2437 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2438 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002439 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002440
2441 // An API NetworkStateTrackers can call when they lose their network.
2442 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2443 // whichever happens first. The timer is started by the first caller and not
2444 // restarted by subsequent callers.
2445 public void requestNetworkTransitionWakelock(String forWhom) {
2446 enforceConnectivityInternalPermission();
2447 synchronized (this) {
2448 if (mNetTransitionWakeLock.isHeld()) return;
2449 mNetTransitionWakeLockSerialNumber++;
2450 mNetTransitionWakeLock.acquire();
2451 mNetTransitionWakeLockCausedBy = forWhom;
2452 }
2453 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002454 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002455 mNetTransitionWakeLockSerialNumber, 0),
2456 mNetTransitionWakeLockTimeout);
2457 return;
2458 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002459
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002460 // 100 percent is full good, 0 is full bad.
2461 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002462 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002463 mContext.enforceCallingOrSelfPermission(
2464 android.Manifest.permission.STATUS_BAR,
2465 "ConnectivityService");
2466
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002467 if (DBG) {
2468 int pid = getCallingPid();
2469 int uid = getCallingUid();
2470 String s = pid + "(" + uid + ") reports inet is " +
2471 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2472 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2473 mInetLog.add(s);
2474 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2475 mInetLog.remove(0);
2476 }
2477 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002478 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002479 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2480 }
2481
2482 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002483 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002484 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002485 return;
2486 }
2487 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07002488 if (DBG) log("handleInetConditionChange: net=" + netType +
2489 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002490 return;
2491 }
Wink Savillec9acde92011-09-21 11:05:43 -07002492 if (VDBG) {
2493 log("handleInetConditionChange: net=" +
2494 netType + ", condition=" + condition +
2495 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2496 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002497 mDefaultInetCondition = condition;
2498 int delay;
2499 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002500 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002501 // setup a new hold to debounce this
2502 if (mDefaultInetCondition > 50) {
2503 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2504 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2505 } else {
2506 delay = Settings.Secure.getInt(mContext.getContentResolver(),
2507 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2508 }
2509 mInetConditionChangeInFlight = true;
2510 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2511 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2512 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07002513 // we've set the new condition, when this hold ends that will get picked up
2514 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002515 }
2516 }
2517
2518 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002519 if (DBG) {
2520 log("handleInetConditionHoldEnd: net=" + netType +
2521 ", condition=" + mDefaultInetCondition +
2522 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002523 }
2524 mInetConditionChangeInFlight = false;
2525
2526 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002527 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002528 return;
2529 }
2530 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07002531 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002532 return;
2533 }
Wink Saville628b0852011-08-04 15:01:58 -07002534 // TODO: Figure out why this optimization sometimes causes a
2535 // change in mDefaultInetCondition to be missed and the
2536 // UI to not be updated.
2537 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2538 // if (DBG) log("no change in condition - aborting");
2539 // return;
2540 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002541 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2542 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002543 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002544 return;
2545 }
2546 mDefaultInetConditionPublished = mDefaultInetCondition;
2547 sendInetConditionBroadcast(networkInfo);
2548 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002549 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002550
2551 public synchronized ProxyProperties getProxy() {
2552 if (mGlobalProxy != null) return mGlobalProxy;
2553 if (mDefaultProxy != null) return mDefaultProxy;
2554 return null;
2555 }
2556
2557 public void setGlobalProxy(ProxyProperties proxyProperties) {
2558 enforceChangePermission();
2559 synchronized (mGlobalProxyLock) {
2560 if (proxyProperties == mGlobalProxy) return;
2561 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2562 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2563
2564 String host = "";
2565 int port = 0;
2566 String exclList = "";
2567 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2568 mGlobalProxy = new ProxyProperties(proxyProperties);
2569 host = mGlobalProxy.getHost();
2570 port = mGlobalProxy.getPort();
2571 exclList = mGlobalProxy.getExclusionList();
2572 } else {
2573 mGlobalProxy = null;
2574 }
2575 ContentResolver res = mContext.getContentResolver();
2576 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2577 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002578 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07002579 exclList);
2580 }
2581
2582 if (mGlobalProxy == null) {
2583 proxyProperties = mDefaultProxy;
2584 }
2585 sendProxyBroadcast(proxyProperties);
2586 }
2587
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002588 private void loadGlobalProxy() {
2589 ContentResolver res = mContext.getContentResolver();
2590 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2591 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2592 String exclList = Settings.Secure.getString(res,
2593 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2594 if (!TextUtils.isEmpty(host)) {
2595 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2596 synchronized (mGlobalProxyLock) {
2597 mGlobalProxy = proxyProperties;
2598 }
2599 }
2600 }
2601
Robert Greenwalt434203a2010-10-11 16:00:27 -07002602 public ProxyProperties getGlobalProxy() {
2603 synchronized (mGlobalProxyLock) {
2604 return mGlobalProxy;
2605 }
2606 }
2607
2608 private void handleApplyDefaultProxy(int type) {
2609 // check if new default - push it out to all VM if so
2610 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2611 synchronized (this) {
2612 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2613 if (mDefaultProxy == proxy) return;
Robert Greenwaltfde1eb72011-07-29 10:03:37 -07002614 if (proxy != null && !TextUtils.isEmpty(proxy.getHost())) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002615 mDefaultProxy = proxy;
2616 } else {
2617 mDefaultProxy = null;
2618 }
2619 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002620 if (VDBG) log("changing default proxy to " + proxy);
Robert Greenwalt0e090822011-09-21 16:37:34 -07002621
2622 // global trumps default, if set, ignore this.
Robert Greenwalt434203a2010-10-11 16:00:27 -07002623 if (mGlobalProxy != null) return;
2624 sendProxyBroadcast(proxy);
2625 }
2626
2627 private void handleDeprecatedGlobalHttpProxy() {
2628 String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2629 Settings.Secure.HTTP_PROXY);
2630 if (!TextUtils.isEmpty(proxy)) {
2631 String data[] = proxy.split(":");
2632 String proxyHost = data[0];
2633 int proxyPort = 8080;
2634 if (data.length > 1) {
2635 try {
2636 proxyPort = Integer.parseInt(data[1]);
2637 } catch (NumberFormatException e) {
2638 return;
2639 }
2640 }
2641 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2642 setGlobalProxy(p);
2643 }
2644 }
2645
2646 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08002647 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002648 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002649 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002650 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2651 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002652 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Robert Greenwalta2e13392010-12-06 11:29:17 -08002653 mContext.sendStickyBroadcast(intent);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002654 }
2655
2656 private static class SettingsObserver extends ContentObserver {
2657 private int mWhat;
2658 private Handler mHandler;
2659 SettingsObserver(Handler handler, int what) {
2660 super(handler);
2661 mHandler = handler;
2662 mWhat = what;
2663 }
2664
2665 void observe(Context context) {
2666 ContentResolver resolver = context.getContentResolver();
2667 resolver.registerContentObserver(Settings.Secure.getUriFor(
2668 Settings.Secure.HTTP_PROXY), false, this);
2669 }
2670
2671 @Override
2672 public void onChange(boolean selfChange) {
2673 mHandler.obtainMessage(mWhat).sendToTarget();
2674 }
2675 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002676
2677 private void log(String s) {
2678 Slog.d(TAG, s);
2679 }
2680
2681 private void loge(String s) {
2682 Slog.e(TAG, s);
2683 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002684
repo syncaea743a2011-07-29 23:55:49 -07002685 int convertFeatureToNetworkType(int networkType, String feature) {
2686 int usedNetworkType = networkType;
2687
2688 if(networkType == ConnectivityManager.TYPE_MOBILE) {
2689 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2690 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2691 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2692 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2693 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2694 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2695 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2696 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2697 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2698 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2699 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2700 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2701 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2702 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2703 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2704 } else {
2705 Slog.e(TAG, "Can't match any mobile netTracker!");
2706 }
2707 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2708 if (TextUtils.equals(feature, "p2p")) {
2709 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2710 } else {
2711 Slog.e(TAG, "Can't match any wifi netTracker!");
2712 }
2713 } else {
2714 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002715 }
repo syncaea743a2011-07-29 23:55:49 -07002716 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08002717 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002718
2719 private static <T> T checkNotNull(T value, String message) {
2720 if (value == null) {
2721 throw new NullPointerException(message);
2722 }
2723 return value;
2724 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002725
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002726 /**
2727 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002728 * VpnBuilder and not available in ConnectivityManager. Permissions
2729 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002730 * @hide
2731 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002732 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07002733 public boolean protectVpn(ParcelFileDescriptor socket) {
2734 try {
2735 int type = mActiveDefaultNetwork;
2736 if (ConnectivityManager.isNetworkTypeValid(type)) {
2737 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
2738 return true;
2739 }
2740 } catch (Exception e) {
2741 // ignore
2742 } finally {
2743 try {
2744 socket.close();
2745 } catch (Exception e) {
2746 // ignore
2747 }
2748 }
2749 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002750 }
2751
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002752 /**
2753 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002754 * and not available in ConnectivityManager. Permissions are checked
2755 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002756 * @hide
2757 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002758 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002759 public boolean prepareVpn(String oldPackage, String newPackage) {
2760 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002761 }
2762
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002763 /**
2764 * Configure a TUN interface and return its file descriptor. Parameters
2765 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002766 * and not available in ConnectivityManager. Permissions are checked in
2767 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002768 * @hide
2769 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002770 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002771 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002772 return mVpn.establish(config);
2773 }
2774
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002775 /**
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002776 * Start legacy VPN and return an intent to VpnDialogs. This method is
2777 * used by VpnSettings and not available in ConnectivityManager.
2778 * Permissions are checked in Vpn class.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002779 * @hide
2780 */
2781 @Override
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002782 public void startLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) {
2783 mVpn.startLegacyVpn(config, racoon, mtpd);
2784 }
2785
2786 /**
2787 * Return the information of the ongoing legacy VPN. This method is used
2788 * by VpnSettings and not available in ConnectivityManager. Permissions
2789 * are checked in Vpn class.
2790 * @hide
2791 */
2792 @Override
2793 public LegacyVpnInfo getLegacyVpnInfo() {
2794 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002795 }
2796
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002797 /**
2798 * Callback for VPN subsystem. Currently VPN is not adapted to the service
2799 * through NetworkStateTracker since it works differently. For example, it
2800 * needs to override DNS servers but never takes the default routes. It
2801 * relies on another data network, and it could keep existing connections
2802 * alive after reconnecting, switching between networks, or even resuming
2803 * from deep sleep. Calls from applications should be done synchronously
2804 * to avoid race conditions. As these are all hidden APIs, refactoring can
2805 * be done whenever a better abstraction is developed.
2806 */
2807 public class VpnCallback {
2808
2809 private VpnCallback() {
2810 }
2811
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002812 public void override(List<String> dnsServers, List<String> searchDomains) {
2813 if (dnsServers == null) {
2814 restore();
2815 return;
2816 }
2817
2818 // Convert DNS servers into addresses.
2819 List<InetAddress> addresses = new ArrayList<InetAddress>();
2820 for (String address : dnsServers) {
2821 // Double check the addresses and remove invalid ones.
2822 try {
2823 addresses.add(InetAddress.parseNumericAddress(address));
2824 } catch (Exception e) {
2825 // ignore
2826 }
2827 }
2828 if (addresses.isEmpty()) {
2829 restore();
2830 return;
2831 }
2832
2833 // Concatenate search domains into a string.
2834 StringBuilder buffer = new StringBuilder();
2835 if (searchDomains != null) {
2836 for (String domain : searchDomains) {
2837 buffer.append(domain).append(' ');
2838 }
2839 }
2840 String domains = buffer.toString().trim();
2841
2842 // Apply DNS changes.
2843 boolean changed = false;
2844 synchronized (mDnsLock) {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002845 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002846 mDnsOverridden = true;
2847 }
2848 if (changed) {
2849 bumpDns();
2850 }
2851
2852 // TODO: temporarily remove http proxy?
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002853 }
2854
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002855 public void restore() {
2856 synchronized (mDnsLock) {
2857 if (!mDnsOverridden) {
2858 return;
2859 }
2860 mDnsOverridden = false;
2861 }
2862 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002863 }
2864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865}