blob: 4c22ae8cb377a985e958b2ef8a85bba72eb51ce7 [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 Sharkey69ddab42012-08-25 00:05:46 -070019import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1a303952011-06-16 13:04:20 -070020import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baidb3c8672012-06-20 14:29:57 -070021import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070022import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
23import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
25import static android.net.ConnectivityManager.TYPE_DUMMY;
26import static android.net.ConnectivityManager.TYPE_ETHERNET;
27import static android.net.ConnectivityManager.TYPE_MOBILE;
28import static android.net.ConnectivityManager.TYPE_WIFI;
29import static android.net.ConnectivityManager.TYPE_WIMAX;
30import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.ConnectivityManager.isNetworkTypeValid;
32import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Irfan Sheriff9538bdd2012-09-20 09:32:41 -070035import android.app.Activity;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080036import android.bluetooth.BluetoothTetheringDataTracker;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070037import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.ContentResolver;
39import android.content.Context;
tk.mun148c7d02011-10-13 22:51:57 +090040import android.content.ContextWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070042import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.PackageManager;
tk.mun148c7d02011-10-13 22:51:57 +090044import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070045import android.database.ContentObserver;
Irfan Sheriffda6da092012-08-16 12:49:23 -070046import android.net.CaptivePortalTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.net.ConnectivityManager;
Robert Greenwaltda3d5e62010-12-06 13:56:24 -080048import android.net.DummyDataStateTracker;
Benoit Goby19970692010-12-22 14:29:40 -080049import android.net.EthernetDataTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070051import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070052import android.net.INetworkPolicyListener;
53import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070054import android.net.INetworkStatsService;
Wink Savillec9822c52011-07-14 12:23:28 -070055import android.net.LinkAddress;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080056import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070057import android.net.LinkProperties.CompareResult;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.net.MobileDataStateTracker;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070059import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070061import android.net.NetworkInfo.DetailedState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070062import android.net.NetworkQuotaInfo;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070063import android.net.NetworkState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.net.NetworkStateTracker;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070065import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070066import android.net.Proxy;
67import android.net.ProxyProperties;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070068import android.net.RouteInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.net.wifi.WifiStateTracker;
tk.mun148c7d02011-10-13 22:51:57 +090070import android.net.wimax.WimaxManagerConstants;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Binder;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040072import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070074import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070075import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070076import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Looper;
78import android.os.Message;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070079import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070080import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070081import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070082import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.ServiceManager;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070084import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070086import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070088import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070089import android.security.KeyStore;
Robert Greenwalt42acef32009-08-12 16:08:25 -070090import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080092import android.util.Slog;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070093import android.util.SparseIntArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
Chia-chi Yeh2e467642011-07-04 03:23:12 -070095import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -070096import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -070097import com.android.internal.net.VpnProfile;
Robert Greenwalt42acef32009-08-12 16:08:25 -070098import com.android.internal.telephony.Phone;
Wink Savillea639b312012-07-10 12:37:54 -070099import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700100import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700101import com.android.server.am.BatteryStatsService;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800102import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700103import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700104import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700105import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700106import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700107import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700108
tk.mun148c7d02011-10-13 22:51:57 +0900109import dalvik.system.DexClassLoader;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.io.FileDescriptor;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700112import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.io.PrintWriter;
tk.mun148c7d02011-10-13 22:51:57 +0900114import java.lang.reflect.Constructor;
Wink Savillec9822c52011-07-14 12:23:28 -0700115import java.net.Inet4Address;
Wink Savillee8222252011-07-13 13:44:13 -0700116import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700117import java.net.InetAddress;
118import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700119import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700120import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700121import java.util.Collection;
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700122import java.util.GregorianCalendar;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700123import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700124import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
126/**
127 * @hide
128 */
129public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700130 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131
Robert Greenwaltba175a52010-10-05 19:12:26 -0700132 private static final boolean DBG = true;
Wink Savillec9acde92011-09-21 11:05:43 -0700133 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700135 private static final boolean LOGD_RULES = false;
136
Jeff Sharkey899223b2012-08-04 15:24:58 -0700137 // TODO: create better separation between radio types and network types
138
Robert Greenwalt42acef32009-08-12 16:08:25 -0700139 // how long to wait before switching back to a radio's default network
140 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
141 // system property that can override the above value
142 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
143 "android.telephony.apn-restore";
144
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700145 // used in recursive route setting to add gateways for the host for which
146 // a host route was requested.
147 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
148
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800149 private Tethering mTethering;
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800150 private boolean mTetheringConfigValid = false;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800151
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700152 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700153
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700154 private Vpn mVpn;
Jeff Sharkey899223b2012-08-04 15:24:58 -0700155 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700156
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700157 private boolean mLockdownEnabled;
158 private LockdownVpnTracker mLockdownTracker;
159
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700160 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
161 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700162 /** Currently active network rules by UID. */
163 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700164 /** Set of ifaces that are costly. */
165 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 /**
168 * Sometimes we want to refer to the individual network state
169 * trackers separately, and sometimes we just want to treat them
170 * abstractly.
171 */
172 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt42acef32009-08-12 16:08:25 -0700173
Irfan Sheriffda6da092012-08-16 12:49:23 -0700174 /* Handles captive portal check on a network */
175 private CaptivePortalTracker mCaptivePortalTracker;
176
Robert Greenwalt42acef32009-08-12 16:08:25 -0700177 /**
Wink Savillee8222252011-07-13 13:44:13 -0700178 * The link properties that define the current links
179 */
180 private LinkProperties mCurrentLinkProperties[];
181
182 /**
Robert Greenwalt42acef32009-08-12 16:08:25 -0700183 * A per Net list of the PID's that requested access to the net
184 * used both as a refcount and for per-PID DNS selection
185 */
186 private List mNetRequestersPids[];
187
Robert Greenwalt42acef32009-08-12 16:08:25 -0700188 // priority order of the nettrackers
189 // (excluding dynamically set mNetworkPreference)
190 // TODO - move mNetworkTypePreference into this
191 private int[] mPriorityList;
192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private Context mContext;
194 private int mNetworkPreference;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700195 private int mActiveDefaultNetwork = -1;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700196 // 0 is full bad, 100 is full good
197 private int mDefaultInetCondition = 0;
198 private int mDefaultInetConditionPublished = 0;
199 private boolean mInetConditionChangeInFlight = false;
200 private int mDefaultConnectionSequence = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700202 private Object mDnsLock = new Object();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 private int mNumDnsEntries;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700204 private boolean mDnsOverridden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
206 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700207 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700209 private INetworkManagementService mNetd;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700210 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700211
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700212 private static final int ENABLED = 1;
213 private static final int DISABLED = 0;
214
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700215 private static final boolean ADD = true;
216 private static final boolean REMOVE = false;
217
218 private static final boolean TO_DEFAULT_TABLE = true;
219 private static final boolean TO_SECONDARY_TABLE = false;
220
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700221 /**
222 * used internally as a delayed event to make us switch back to the
223 * default network
224 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700225 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700226
227 /**
228 * used internally to change our mobile data enabled flag
229 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700230 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700231
232 /**
233 * used internally to change our network preference setting
234 * arg1 = networkType to prefer
235 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700236 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237
238 /**
239 * used internally to synchronize inet condition reports
240 * arg1 = networkType
241 * arg2 = condition (0 bad, 100 good)
242 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700243 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700244
245 /**
246 * used internally to mark the end of inet condition hold periods
247 * arg1 = networkType
248 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700249 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700250
251 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700252 * used internally to set enable/disable cellular data
253 * arg1 = ENBALED or DISABLED
254 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700255 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700256
Robert Greenwaltf3331232010-09-24 14:32:21 -0700257 /**
258 * used internally to clear a wakelock when transitioning
259 * from one net to another
260 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700261 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700262
Robert Greenwalt434203a2010-10-11 16:00:27 -0700263 /**
264 * used internally to reload global proxy settings
265 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700266 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700267
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700268 /**
269 * used internally to set external dependency met/unmet
270 * arg1 = ENABLED (met) or DISABLED (unmet)
271 * arg2 = NetworkType
272 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700273 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700274
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700275 /**
276 * used internally to restore DNS properties back to the
277 * default network
278 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700279 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700280
Wink Saville2b30afd2011-08-05 11:40:22 -0700281 /**
Wink Saville628b0852011-08-04 15:01:58 -0700282 * used internally to send a sticky broadcast delayed.
283 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700284 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville628b0852011-08-04 15:01:58 -0700285
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700286 /**
287 * Used internally to
288 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
289 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700290 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700291
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700292 private static final int EVENT_VPN_STATE_CHANGED = 14;
293
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700294 /** Handler used for internal events. */
295 private InternalHandler mHandler;
296 /** Handler used for incoming {@link NetworkStateTracker} events. */
297 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700298
299 // list of DeathRecipients used to make sure features are turned off when
300 // a process dies
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500301 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700302
Mike Lockwood0f79b542009-08-14 14:18:49 -0400303 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800304 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400305
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700306 private PowerManager.WakeLock mNetTransitionWakeLock;
307 private String mNetTransitionWakeLockCausedBy = "";
308 private int mNetTransitionWakeLockSerialNumber;
309 private int mNetTransitionWakeLockTimeout;
310
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700311 private InetAddress mDefaultDns;
312
Robert Greenwalt0a46db52011-07-14 14:28:05 -0700313 // this collection is used to refcount the added routes - if there are none left
314 // it's time to remove the route from the route table
315 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
316
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700317 // used in DBG mode to track inet condition reports
318 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
319 private ArrayList mInetLog;
320
Robert Greenwalt434203a2010-10-11 16:00:27 -0700321 // track the current default http proxy - tell the world if we get a new one (real change)
322 private ProxyProperties mDefaultProxy = null;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700323 private Object mDefaultProxyLock = new Object();
324 private boolean mDefaultProxyDisabled = false;
325
Robert Greenwalt434203a2010-10-11 16:00:27 -0700326 // track the global proxy.
327 private ProxyProperties mGlobalProxy = null;
328 private final Object mGlobalProxyLock = new Object();
329
330 private SettingsObserver mSettingsObserver;
331
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700332 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700333 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700334
Robert Greenwalt511288a2009-12-07 11:33:18 -0800335 private static class RadioAttributes {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700336 public int mSimultaneity;
337 public int mType;
338 public RadioAttributes(String init) {
339 String fragments[] = init.split(",");
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700340 mType = Integer.parseInt(fragments[0]);
341 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700342 }
343 }
344 RadioAttributes[] mRadioAttributes;
345
Robert Greenwalt50393202011-06-21 17:26:14 -0700346 // the set of network types that can only be enabled by system/sig apps
347 List mProtectedNetworks;
348
Jeff Sharkey367d15a2011-09-22 14:59:51 -0700349 public ConnectivityService(Context context, INetworkManagementService netd,
350 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700351 // Currently, omitting a NetworkFactory will create one internally
352 // TODO: create here when we have cleaner WiMAX support
353 this(context, netd, statsService, policyManager, null);
354 }
355
Jeff Sharkey899223b2012-08-04 15:24:58 -0700356 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700357 INetworkStatsService statsService, INetworkPolicyManager policyManager,
358 NetworkFactory netFactory) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800359 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800360
Wink Savillebb08caf2010-09-02 19:23:52 -0700361 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
362 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700363 mHandler = new InternalHandler(handlerThread.getLooper());
364 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700365
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700366 if (netFactory == null) {
367 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
368 }
369
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800370 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800371 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
372 String id = Settings.Secure.getString(context.getContentResolver(),
373 Settings.Secure.ANDROID_ID);
374 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700375 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800376 SystemProperties.set("net.hostname", name);
377 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800378 }
379
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700380 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700381 String dns = Settings.Global.getString(context.getContentResolver(),
382 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700383 if (dns == null || dns.length() == 0) {
384 dns = context.getResources().getString(
385 com.android.internal.R.string.config_default_dns_server);
386 }
387 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800388 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
389 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800390 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700391 }
392
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700393 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700394 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700395 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700396 mKeyStore = KeyStore.getInstance();
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700397
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700398 try {
399 mPolicyManager.registerListener(mPolicyListener);
400 } catch (RemoteException e) {
401 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700402 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700403 }
404
405 final PowerManager powerManager = (PowerManager) context.getSystemService(
406 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700407 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
408 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
409 com.android.internal.R.integer.config_networkTransitionTimeout);
410
Robert Greenwalt42acef32009-08-12 16:08:25 -0700411 mNetTrackers = new NetworkStateTracker[
412 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Savillee8222252011-07-13 13:44:13 -0700413 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 mNetworkPreference = getPersistedNetworkPreference();
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700416
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700417 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700418 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700419
Robert Greenwalt42acef32009-08-12 16:08:25 -0700420 // Load device network attributes from resources
Robert Greenwalt42acef32009-08-12 16:08:25 -0700421 String[] raStrings = context.getResources().getStringArray(
422 com.android.internal.R.array.radioAttributes);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700423 for (String raString : raStrings) {
424 RadioAttributes r = new RadioAttributes(raString);
425 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800426 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700427 continue;
428 }
429 if (mRadioAttributes[r.mType] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800430 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700431 r.mType);
432 continue;
433 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700434 mRadioAttributes[r.mType] = r;
435 }
436
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700437 String[] naStrings = context.getResources().getStringArray(
438 com.android.internal.R.array.networkAttributes);
439 for (String naString : naStrings) {
440 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700441 NetworkConfig n = new NetworkConfig(naString);
Wink Saville975c8482011-04-07 14:23:45 -0700442 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800443 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700444 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700445 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700446 }
Wink Saville975c8482011-04-07 14:23:45 -0700447 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800448 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700449 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700450 continue;
451 }
Wink Saville975c8482011-04-07 14:23:45 -0700452 if (mRadioAttributes[n.radio] == null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800453 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Saville975c8482011-04-07 14:23:45 -0700454 "radio " + n.radio + " in network type " + n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700455 continue;
456 }
Wink Saville975c8482011-04-07 14:23:45 -0700457 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700458 mNetworksDefined++;
459 } catch(Exception e) {
460 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700461 }
462 }
463
Robert Greenwalt50393202011-06-21 17:26:14 -0700464 mProtectedNetworks = new ArrayList<Integer>();
465 int[] protectedNetworks = context.getResources().getIntArray(
466 com.android.internal.R.array.config_protectedNetworks);
467 for (int p : protectedNetworks) {
468 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
469 mProtectedNetworks.add(p);
470 } else {
471 if (DBG) loge("Ignoring protectedNetwork " + p);
472 }
473 }
474
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700475 // high priority first
476 mPriorityList = new int[mNetworksDefined];
477 {
478 int insertionPoint = mNetworksDefined-1;
479 int currentLowest = 0;
480 int nextLowest = 0;
481 while (insertionPoint > -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700482 for (NetworkConfig na : mNetConfigs) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700483 if (na == null) continue;
Wink Saville975c8482011-04-07 14:23:45 -0700484 if (na.priority < currentLowest) continue;
485 if (na.priority > currentLowest) {
486 if (na.priority < nextLowest || nextLowest == 0) {
487 nextLowest = na.priority;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700488 }
489 continue;
490 }
Wink Saville975c8482011-04-07 14:23:45 -0700491 mPriorityList[insertionPoint--] = na.type;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700492 }
493 currentLowest = nextLowest;
494 nextLowest = 0;
495 }
496 }
497
498 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
499 for (int i : mPriorityList) {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700500 mNetRequestersPids[i] = new ArrayList();
501 }
502
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -0500503 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt42acef32009-08-12 16:08:25 -0700504
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700505 mNumDnsEntries = 0;
506
507 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
508 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700509
510 // Create and start trackers for hard-coded networks
511 for (int targetNetworkType : mPriorityList) {
512 final NetworkConfig config = mNetConfigs[targetNetworkType];
513 final NetworkStateTracker tracker;
514 try {
515 tracker = netFactory.createTracker(targetNetworkType, config);
516 mNetTrackers[targetNetworkType] = tracker;
517 } catch (IllegalArgumentException e) {
518 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
519 + " tracker: " + e);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700520 continue;
521 }
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700522
523 tracker.startMonitoring(context, mTrackerHandler);
524 if (config.isDefault()) {
525 tracker.reconnect();
Robert Greenwalt6537b022011-11-10 16:55:20 -0800526 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700527 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800528
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700529 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700530 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang6fdd0c62010-08-11 14:54:43 -0700531 mTethering.getTetherableWifiRegexs().length != 0 ||
532 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwaltccf83af12011-06-02 17:30:47 -0700533 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800534
Jeff Sharkey899223b2012-08-04 15:24:58 -0700535 mVpn = new Vpn(mContext, mVpnCallback, mNetd);
536 mVpn.startMonitoring(mContext, mTrackerHandler);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700537
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700538 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700539 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700540 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700541 } catch (RemoteException e) {
542 loge("Error registering observer :" + e);
543 }
544
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700545 if (DBG) {
546 mInetLog = new ArrayList();
547 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700548
549 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
550 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800551
Irfan Sheriff9538bdd2012-09-20 09:32:41 -0700552 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800553 loadGlobalProxy();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700555
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700556 /**
557 * Factory that creates {@link NetworkStateTracker} instances using given
558 * {@link NetworkConfig}.
559 */
560 public interface NetworkFactory {
561 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
562 }
563
564 private static class DefaultNetworkFactory implements NetworkFactory {
565 private final Context mContext;
566 private final Handler mTrackerHandler;
567
568 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
569 mContext = context;
570 mTrackerHandler = trackerHandler;
571 }
572
573 @Override
574 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
575 switch (config.radio) {
576 case TYPE_WIFI:
577 return new WifiStateTracker(targetNetworkType, config.name);
578 case TYPE_MOBILE:
579 return new MobileDataStateTracker(targetNetworkType, config.name);
580 case TYPE_DUMMY:
581 return new DummyDataStateTracker(targetNetworkType, config.name);
582 case TYPE_BLUETOOTH:
583 return BluetoothTetheringDataTracker.getInstance();
584 case TYPE_WIMAX:
585 return makeWimaxStateTracker(mContext, mTrackerHandler);
586 case TYPE_ETHERNET:
587 return EthernetDataTracker.getInstance();
588 default:
589 throw new IllegalArgumentException(
590 "Trying to create a NetworkStateTracker for an unknown radio type: "
591 + config.radio);
592 }
593 }
594 }
595
596 /**
597 * Loads external WiMAX library and registers as system service, returning a
598 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
599 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
600 */
601 private static NetworkStateTracker makeWimaxStateTracker(
602 Context context, Handler trackerHandler) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700603 // Initialize Wimax
tk.mun148c7d02011-10-13 22:51:57 +0900604 DexClassLoader wimaxClassLoader;
605 Class wimaxStateTrackerClass = null;
606 Class wimaxServiceClass = null;
607 Class wimaxManagerClass;
608 String wimaxJarLocation;
609 String wimaxLibLocation;
610 String wimaxManagerClassName;
611 String wimaxServiceClassName;
612 String wimaxStateTrackerClassName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613
tk.mun148c7d02011-10-13 22:51:57 +0900614 NetworkStateTracker wimaxStateTracker = null;
615
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700616 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun148c7d02011-10-13 22:51:57 +0900617 com.android.internal.R.bool.config_wimaxEnabled);
618
619 if (isWimaxEnabled) {
620 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700621 wimaxJarLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900622 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700623 wimaxLibLocation = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900624 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700625 wimaxManagerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900626 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700627 wimaxServiceClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900628 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700629 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun148c7d02011-10-13 22:51:57 +0900630 com.android.internal.R.string.config_wimaxStateTrackerClassname);
631
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800632 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun148c7d02011-10-13 22:51:57 +0900633 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700634 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun148c7d02011-10-13 22:51:57 +0900635 wimaxLibLocation, ClassLoader.getSystemClassLoader());
636
637 try {
638 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
639 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
640 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
641 } catch (ClassNotFoundException ex) {
642 loge("Exception finding Wimax classes: " + ex.toString());
643 return null;
644 }
645 } catch(Resources.NotFoundException ex) {
646 loge("Wimax Resources does not exist!!! ");
647 return null;
648 }
649
650 try {
Dianne Hackborn7ff30112012-11-08 11:12:09 -0800651 if (DBG) log("Starting Wimax Service... ");
tk.mun148c7d02011-10-13 22:51:57 +0900652
653 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
654 (new Class[] {Context.class, Handler.class});
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700655 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
656 context, trackerHandler);
tk.mun148c7d02011-10-13 22:51:57 +0900657
658 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
659 (new Class[] {Context.class, wimaxStateTrackerClass});
660 wmxSrvConst.setAccessible(true);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700661 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun148c7d02011-10-13 22:51:57 +0900662 wmxSrvConst.setAccessible(false);
663
664 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
665
666 } catch(Exception ex) {
667 loge("Exception creating Wimax classes: " + ex.toString());
668 return null;
669 }
670 } else {
671 loge("Wimax is not enabled or not added to the network attributes!!! ");
672 return null;
673 }
674
675 return wimaxStateTracker;
676 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700679 * Sets the preferred network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 * @param preference the new preference
681 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700682 public void setNetworkPreference(int preference) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 enforceChangePermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700684
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700685 mHandler.sendMessage(
686 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 }
688
689 public int getNetworkPreference() {
690 enforceAccessPermission();
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700691 int preference;
692 synchronized(this) {
693 preference = mNetworkPreference;
694 }
695 return preference;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 }
697
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700698 private void handleSetNetworkPreference(int preference) {
699 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700700 mNetConfigs[preference] != null &&
701 mNetConfigs[preference].isDefault()) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700702 if (mNetworkPreference != preference) {
703 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700704 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700705 synchronized(this) {
706 mNetworkPreference = preference;
707 }
708 enforcePreference();
709 }
710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700712
Wink Saville628b0852011-08-04 15:01:58 -0700713 private int getConnectivityChangeDelay() {
714 final ContentResolver cr = mContext.getContentResolver();
715
716 /** Check system properties for the default value then use secure settings value, if any. */
717 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey625239a2012-09-26 22:03:49 -0700718 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
719 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
720 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville628b0852011-08-04 15:01:58 -0700721 defaultDelay);
722 }
723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 private int getPersistedNetworkPreference() {
725 final ContentResolver cr = mContext.getContentResolver();
726
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700727 final int networkPrefSetting = Settings.Global
728 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 if (networkPrefSetting != -1) {
730 return networkPrefSetting;
731 }
732
733 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
734 }
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700737 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 * In this method, we only tear down a non-preferred network. Establishing
739 * a connection to the preferred network is taken care of when we handle
740 * the disconnect event from the non-preferred network
741 * (see {@link #handleDisconnect(NetworkInfo)}).
742 */
743 private void enforcePreference() {
Robert Greenwalt42acef32009-08-12 16:08:25 -0700744 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 return;
746
Robert Greenwalt42acef32009-08-12 16:08:25 -0700747 if (!mNetTrackers[mNetworkPreference].isAvailable())
748 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749
Robert Greenwalt42acef32009-08-12 16:08:25 -0700750 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700751 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt42acef32009-08-12 16:08:25 -0700752 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700753 if (DBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800754 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltec9fe462009-08-20 15:25:14 -0700755 " in enforcePreference");
756 }
Robert Greenwalt42acef32009-08-12 16:08:25 -0700757 teardown(mNetTrackers[t]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 }
759 }
760 }
761
762 private boolean teardown(NetworkStateTracker netTracker) {
763 if (netTracker.teardown()) {
764 netTracker.setTeardownRequested(true);
765 return true;
766 } else {
767 return false;
768 }
769 }
770
771 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700772 * Check if UID should be blocked from using the network represented by the
773 * given {@link NetworkStateTracker}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700774 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700775 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
776 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700777
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700778 final boolean networkCostly;
779 final int uidRules;
780 synchronized (mRulesLock) {
781 networkCostly = mMeteredIfaces.contains(iface);
782 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700783 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700784
785 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
786 return true;
787 }
788
789 // no restrictive rules; network is visible
790 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700791 }
792
793 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700794 * Return a filtered {@link NetworkInfo}, potentially marked
795 * {@link DetailedState#BLOCKED} based on
796 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700797 */
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700798 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
799 NetworkInfo info = tracker.getNetworkInfo();
800 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700801 // network is blocked; clone and override state
802 info = new NetworkInfo(info);
803 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700804 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700805 if (mLockdownTracker != null) {
806 info = mLockdownTracker.augmentNetworkInfo(info);
807 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700808 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700809 }
810
811 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 * Return NetworkInfo for the active (i.e., connected) network interface.
813 * It is assumed that at most one network is active at a time. If more
814 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700815 * @return the info for the active network, or {@code null} if none is
816 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700818 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700820 enforceAccessPermission();
821 final int uid = Binder.getCallingUid();
822 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 }
824
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700825 public NetworkInfo getActiveNetworkInfoUnfiltered() {
826 enforceAccessPermission();
827 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
828 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
829 if (tracker != null) {
830 return tracker.getNetworkInfo();
831 }
832 }
833 return null;
834 }
835
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700836 @Override
837 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
838 enforceConnectivityInternalPermission();
839 return getNetworkInfo(mActiveDefaultNetwork, uid);
840 }
841
842 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 public NetworkInfo getNetworkInfo(int networkType) {
844 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700845 final int uid = Binder.getCallingUid();
846 return getNetworkInfo(networkType, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 }
848
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700849 private NetworkInfo getNetworkInfo(int networkType, int uid) {
850 NetworkInfo info = null;
851 if (isNetworkTypeValid(networkType)) {
852 final NetworkStateTracker tracker = mNetTrackers[networkType];
853 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700854 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700855 }
856 }
857 return info;
858 }
859
860 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 public NetworkInfo[] getAllNetworkInfo() {
862 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700863 final int uid = Binder.getCallingUid();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700864 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700865 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700866 for (NetworkStateTracker tracker : mNetTrackers) {
867 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700868 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700869 }
870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700872 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
874
Robert Greenwalt9b2886e2011-08-31 11:46:42 -0700875 @Override
876 public boolean isNetworkSupported(int networkType) {
877 enforceAccessPermission();
878 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
879 }
880
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700881 /**
882 * Return LinkProperties for the active (i.e., connected) default
883 * network interface. It is assumed that at most one default network
884 * is active at a time. If more than one is active, it is indeterminate
885 * which will be returned.
886 * @return the ip properties for the active network, or {@code null} if
887 * none is active
888 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700889 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700890 public LinkProperties getActiveLinkProperties() {
Robert Greenwalt59911582011-05-20 12:23:41 -0700891 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700892 }
893
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700894 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700895 public LinkProperties getLinkProperties(int networkType) {
896 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700897 if (isNetworkTypeValid(networkType)) {
898 final NetworkStateTracker tracker = mNetTrackers[networkType];
899 if (tracker != null) {
900 return tracker.getLinkProperties();
901 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -0700902 }
903 return null;
904 }
905
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700906 @Override
907 public NetworkState[] getAllNetworkState() {
908 enforceAccessPermission();
909 final int uid = Binder.getCallingUid();
910 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700911 synchronized (mRulesLock) {
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700912 for (NetworkStateTracker tracker : mNetTrackers) {
913 if (tracker != null) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700914 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700915 result.add(new NetworkState(
916 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
917 }
918 }
919 }
920 return result.toArray(new NetworkState[result.size()]);
921 }
922
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700923 private NetworkState getNetworkStateUnchecked(int networkType) {
924 if (isNetworkTypeValid(networkType)) {
925 final NetworkStateTracker tracker = mNetTrackers[networkType];
926 if (tracker != null) {
927 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
928 tracker.getLinkCapabilities());
929 }
930 }
931 return null;
932 }
933
934 @Override
935 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
936 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700937
938 final long token = Binder.clearCallingIdentity();
939 try {
940 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
941 if (state != null) {
942 try {
943 return mPolicyManager.getNetworkQuotaInfo(state);
944 } catch (RemoteException e) {
945 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700946 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700947 return null;
948 } finally {
949 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700950 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700951 }
952
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700953 @Override
954 public boolean isActiveNetworkMetered() {
955 enforceAccessPermission();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700956 final long token = Binder.clearCallingIdentity();
957 try {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -0700958 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -0700959 } finally {
960 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700961 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -0700962 }
963
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -0700964 private boolean isNetworkMeteredUnchecked(int networkType) {
965 final NetworkState state = getNetworkStateUnchecked(networkType);
966 if (state != null) {
967 try {
968 return mPolicyManager.isNetworkMetered(state);
969 } catch (RemoteException e) {
970 }
971 }
972 return false;
973 }
974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 public boolean setRadios(boolean turnOn) {
976 boolean result = true;
977 enforceChangePermission();
978 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700979 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 }
981 return result;
982 }
983
984 public boolean setRadio(int netType, boolean turnOn) {
985 enforceChangePermission();
986 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
987 return false;
988 }
989 NetworkStateTracker tracker = mNetTrackers[netType];
990 return tracker != null && tracker.setRadio(turnOn);
991 }
992
Jeff Sharkey216c1812012-08-05 14:29:23 -0700993 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
994 @Override
Haoyu Baidb3c8672012-06-20 14:29:57 -0700995 public void interfaceClassDataActivityChanged(String label, boolean active) {
996 int deviceType = Integer.parseInt(label);
997 sendDataActivityBroadcast(deviceType, active);
998 }
Jeff Sharkey216c1812012-08-05 14:29:23 -0700999 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001000
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001001 /**
1002 * Used to notice when the calling process dies so we can self-expire
1003 *
1004 * Also used to know if the process has cleaned up after itself when
1005 * our auto-expire timer goes off. The timer has a link to an object.
1006 *
1007 */
Robert Greenwalt42acef32009-08-12 16:08:25 -07001008 private class FeatureUser implements IBinder.DeathRecipient {
1009 int mNetworkType;
1010 String mFeature;
1011 IBinder mBinder;
1012 int mPid;
1013 int mUid;
Robert Greenwaltb9285352009-12-21 18:24:07 -08001014 long mCreateTime;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001015
1016 FeatureUser(int type, String feature, IBinder binder) {
1017 super();
1018 mNetworkType = type;
1019 mFeature = feature;
1020 mBinder = binder;
1021 mPid = getCallingPid();
1022 mUid = getCallingUid();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001023 mCreateTime = System.currentTimeMillis();
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001024
Robert Greenwalt42acef32009-08-12 16:08:25 -07001025 try {
1026 mBinder.linkToDeath(this, 0);
1027 } catch (RemoteException e) {
1028 binderDied();
1029 }
1030 }
1031
1032 void unlinkDeathRecipient() {
1033 mBinder.unlinkToDeath(this, 0);
1034 }
1035
1036 public void binderDied() {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001037 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwaltb9285352009-12-21 18:24:07 -08001038 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1039 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001040 stopUsingNetworkFeature(this, false);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001041 }
1042
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001043 public void expire() {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001044 if (VDBG) {
1045 log("ConnectivityService FeatureUser expire(" +
1046 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1047 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1048 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001049 stopUsingNetworkFeature(this, false);
1050 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08001051
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001052 public boolean isSameUser(FeatureUser u) {
1053 if (u == null) return false;
1054
1055 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1056 }
1057
1058 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1059 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1060 TextUtils.equals(mFeature, feature)) {
1061 return true;
1062 }
1063 return false;
1064 }
1065
Robert Greenwaltb9285352009-12-21 18:24:07 -08001066 public String toString() {
1067 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1068 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1069 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001070 }
1071
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001072 // javadoc from interface
Robert Greenwalt42acef32009-08-12 16:08:25 -07001073 public int startUsingNetworkFeature(int networkType, String feature,
1074 IBinder binder) {
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001075 long startTime = 0;
1076 if (DBG) {
1077 startTime = SystemClock.elapsedRealtime();
1078 }
Wink Savillec9acde92011-09-21 11:05:43 -07001079 if (VDBG) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001080 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1081 + Binder.getCallingUid());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 enforceChangePermission();
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001084 try {
1085 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1086 mNetConfigs[networkType] == null) {
Wink Savillea639b312012-07-10 12:37:54 -07001087 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001088 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001089
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001090 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001091
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001092 // TODO - move this into individual networktrackers
1093 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt50393202011-06-21 17:26:14 -07001094
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001095 if (mLockdownEnabled) {
1096 // Since carrier APNs usually aren't available from VPN
1097 // endpoint, mark them as unavailable.
1098 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1099 }
1100
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001101 if (mProtectedNetworks.contains(usedNetworkType)) {
1102 enforceConnectivityInternalPermission();
1103 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001104
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001105 // if UID is restricted, don't allow them to bring up metered APNs
1106 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1107 final int uidRules;
1108 synchronized (mRulesLock) {
1109 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1110 }
1111 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Savillea639b312012-07-10 12:37:54 -07001112 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001113 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001114
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001115 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1116 if (network != null) {
1117 Integer currentPid = new Integer(getCallingPid());
1118 if (usedNetworkType != networkType) {
1119 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001120
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001121 if (ni.isAvailable() == false) {
1122 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1123 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Savillea639b312012-07-10 12:37:54 -07001124 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001125 } else {
1126 // else make the attempt anyway - probably giving REQUEST_STARTED below
1127 if (DBG) {
1128 log("special network not available, but try anyway ni=" +
1129 ni.getTypeName());
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001130 }
1131 }
1132 }
1133
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001134 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001135
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001136 synchronized(this) {
1137 boolean addToList = true;
1138 if (restoreTimer < 0) {
1139 // In case there is no timer is specified for the feature,
1140 // make sure we don't add duplicate entry with the same request.
1141 for (FeatureUser u : mFeatureUsers) {
1142 if (u.isSameUser(f)) {
1143 // Duplicate user is found. Do not add.
1144 addToList = false;
1145 break;
1146 }
1147 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001148 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001149
1150 if (addToList) mFeatureUsers.add(f);
1151 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1152 // this gets used for per-pid dns when connected
1153 mNetRequestersPids[usedNetworkType].add(currentPid);
1154 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001155 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001156
1157 if (restoreTimer >= 0) {
1158 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1159 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1160 }
1161
1162 if ((ni.isConnectedOrConnecting() == true) &&
1163 !network.isTeardownRequested()) {
1164 if (ni.isConnected() == true) {
1165 final long token = Binder.clearCallingIdentity();
1166 try {
1167 // add the pid-specific dns
1168 handleDnsConfigurationChange(usedNetworkType);
1169 if (VDBG) log("special network already active");
1170 } finally {
1171 Binder.restoreCallingIdentity(token);
1172 }
Wink Savillea639b312012-07-10 12:37:54 -07001173 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001174 }
1175 if (VDBG) log("special network already connecting");
Wink Savillea639b312012-07-10 12:37:54 -07001176 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001177 }
1178
1179 // check if the radio in play can make another contact
1180 // assume if cannot for now
1181
1182 if (DBG) {
1183 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1184 feature);
1185 }
1186 network.reconnect();
Wink Savillea639b312012-07-10 12:37:54 -07001187 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001188 } else {
1189 // need to remember this unsupported request so we respond appropriately on stop
1190 synchronized(this) {
1191 mFeatureUsers.add(f);
1192 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1193 // this gets used for per-pid dns when connected
1194 mNetRequestersPids[usedNetworkType].add(currentPid);
1195 }
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001196 }
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001197 return -1;
Robert Greenwalt0be1e982010-12-15 13:26:33 -08001198 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001199 }
Wink Savillea639b312012-07-10 12:37:54 -07001200 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -07001201 } finally {
1202 if (DBG) {
1203 final long execTime = SystemClock.elapsedRealtime() - startTime;
1204 if (execTime > 250) {
1205 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1206 } else {
1207 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1208 }
1209 }
1210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 }
1212
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001213 // javadoc from interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001215 enforceChangePermission();
1216
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001217 int pid = getCallingPid();
1218 int uid = getCallingUid();
1219
1220 FeatureUser u = null;
1221 boolean found = false;
1222
1223 synchronized(this) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001224 for (FeatureUser x : mFeatureUsers) {
1225 if (x.isSameUser(pid, uid, networkType, feature)) {
1226 u = x;
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001227 found = true;
1228 break;
1229 }
1230 }
1231 }
1232 if (found && u != null) {
1233 // stop regardless of how many other time this proc had called start
1234 return stopUsingNetworkFeature(u, true);
1235 } else {
1236 // none found!
Wink Savillec9acde92011-09-21 11:05:43 -07001237 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001238 return 1;
1239 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001240 }
1241
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001242 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1243 int networkType = u.mNetworkType;
1244 String feature = u.mFeature;
1245 int pid = u.mPid;
1246 int uid = u.mUid;
1247
1248 NetworkStateTracker tracker = null;
1249 boolean callTeardown = false; // used to carry our decision outside of sync block
1250
Wink Savillec9acde92011-09-21 11:05:43 -07001251 if (VDBG) {
1252 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001253 }
Robert Greenwaltb8f16342009-10-06 17:52:40 -07001254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001256 if (DBG) {
1257 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1258 ", net is invalid");
1259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 return -1;
1261 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001262
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001263 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1264 // sync block
1265 synchronized(this) {
1266 // check if this process still has an outstanding start request
1267 if (!mFeatureUsers.contains(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001268 if (VDBG) {
1269 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1270 ", ignoring");
1271 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001272 return 1;
1273 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001274 u.unlinkDeathRecipient();
1275 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1276 // If we care about duplicate requests, check for that here.
1277 //
1278 // This is done to support the extension of a request - the app
1279 // can request we start the network feature again and renew the
1280 // auto-shutoff delay. Normal "stop" calls from the app though
1281 // do not pay attention to duplicate requests - in effect the
1282 // API does not refcount and a single stop will counter multiple starts.
1283 if (ignoreDups == false) {
Kazuhiro Ondo3bed4c92011-07-19 11:23:37 -05001284 for (FeatureUser x : mFeatureUsers) {
1285 if (x.isSameUser(u)) {
Wink Savillec9acde92011-09-21 11:05:43 -07001286 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001287 return 1;
1288 }
1289 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001290 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001291
repo syncaea743a2011-07-29 23:55:49 -07001292 // TODO - move to individual network trackers
1293 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1294
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001295 tracker = mNetTrackers[usedNetworkType];
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001296 if (tracker == null) {
Wink Savillec9acde92011-09-21 11:05:43 -07001297 if (DBG) {
1298 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1299 " no known tracker for used net type " + usedNetworkType);
1300 }
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001301 return -1;
1302 }
1303 if (usedNetworkType != networkType) {
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001304 Integer currentPid = new Integer(pid);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001305 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt421c72b2009-12-17 14:54:59 -08001306 reassessPidDns(pid, true);
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001307 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillec9acde92011-09-21 11:05:43 -07001308 if (VDBG) {
1309 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1310 " others still using it");
1311 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001312 return 1;
1313 }
1314 callTeardown = true;
Robert Greenwalt19b9ab42011-01-10 11:58:31 -08001315 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001316 if (DBG) {
1317 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1318 " not a known feature - dropping");
1319 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001320 }
1321 }
Wink Savillec9acde92011-09-21 11:05:43 -07001322
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001323 if (callTeardown) {
Wink Savillec9acde92011-09-21 11:05:43 -07001324 if (DBG) {
1325 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1326 }
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001327 tracker.teardown();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001328 return 1;
1329 } else {
Robert Greenwalt02648a42010-05-18 10:52:51 -07001330 return -1;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 }
1333
1334 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001335 * @deprecated use requestRouteToHostAddress instead
1336 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 * Ensure that a network route exists to deliver traffic to the specified
1338 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001339 * @param networkType the type of the network over which traffic to the
1340 * specified host is to be routed
1341 * @param hostAddress the IP address of the host to which the route is
1342 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 * @return {@code true} on success, {@code false} on failure
1344 */
1345 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001346 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1347
1348 if (inetAddress == null) {
1349 return false;
1350 }
1351
1352 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1353 }
1354
1355 /**
1356 * Ensure that a network route exists to deliver traffic to the specified
1357 * host via the specified network interface.
1358 * @param networkType the type of the network over which traffic to the
1359 * specified host is to be routed
1360 * @param hostAddress the IP address of the host to which the route is
1361 * desired
1362 * @return {@code true} on success, {@code false} on failure
1363 */
1364 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001366 if (mProtectedNetworks.contains(networkType)) {
1367 enforceConnectivityInternalPermission();
1368 }
1369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001371 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 return false;
1373 }
1374 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriffda6da092012-08-16 12:49:23 -07001375 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001376
Irfan Sheriffda6da092012-08-16 12:49:23 -07001377 if (tracker == null || (netState != DetailedState.CONNECTED &&
1378 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001379 tracker.isTeardownRequested()) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001380 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08001381 log("requestRouteToHostAddress on down network " +
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001382 "(" + networkType + ") - dropped");
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001383 }
1384 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
Robert Greenwalt8beff952011-12-13 15:26:02 -08001386 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001387 try {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -07001388 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001389 LinkProperties lp = tracker.getLinkProperties();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001390 return addRouteToAddress(lp, addr);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001391 } catch (UnknownHostException e) {
1392 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1393 } finally {
1394 Binder.restoreCallingIdentity(token);
1395 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001396 return false;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001397 }
1398
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001399 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1400 return modifyRoute(p.getInterfaceName(), p, r, 0, ADD, toDefaultTable);
Robert Greenwaltf43396c2011-05-06 17:10:53 -07001401 }
1402
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001403 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1404 return modifyRoute(p.getInterfaceName(), p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001405 }
1406
Robert Greenwaltad55d352011-07-22 11:55:33 -07001407 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001408 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001409 }
1410
1411 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001412 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001413 }
1414
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001415 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1416 boolean toDefaultTable) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07001417 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), addr);
1418 if (bestRoute == null) {
1419 bestRoute = RouteInfo.makeHostRoute(addr);
1420 } else {
1421 if (bestRoute.getGateway().equals(addr)) {
1422 // if there is no better route, add the implied hostroute for our gateway
1423 bestRoute = RouteInfo.makeHostRoute(addr);
1424 } else {
1425 // if we will connect to this through another route, add a direct route
1426 // to it's gateway
1427 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway());
1428 }
1429 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001430 return modifyRoute(lp.getInterfaceName(), lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001431 }
1432
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001433 private boolean modifyRoute(String ifaceName, LinkProperties lp, RouteInfo r, int cycleCount,
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001434 boolean doAdd, boolean toDefaultTable) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001435 if ((ifaceName == null) || (lp == null) || (r == null)) {
1436 if (DBG) log("modifyRoute got unexpected null: " + ifaceName + ", " + lp + ", " + r);
1437 return false;
1438 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001439
1440 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001441 loge("Error modifying route - too much recursion");
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001442 return false;
1443 }
1444
1445 if (r.isHostRoute() == false) {
1446 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), r.getGateway());
1447 if (bestRoute != null) {
Robert Greenwalt476f5522011-07-15 09:45:08 -07001448 if (bestRoute.getGateway().equals(r.getGateway())) {
1449 // if there is no better route, add the implied hostroute for our gateway
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001450 bestRoute = RouteInfo.makeHostRoute(r.getGateway());
Robert Greenwalt476f5522011-07-15 09:45:08 -07001451 } else {
1452 // if we will connect to our gateway through another route, add a direct
1453 // route to it's gateway
1454 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), bestRoute.getGateway());
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001455 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001456 modifyRoute(ifaceName, lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001457 }
1458 }
1459 if (doAdd) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001460 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001461 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001462 if (toDefaultTable) {
1463 mAddedRoutes.add(r); // only track default table - only one apps can effect
1464 mNetd.addRoute(ifaceName, r);
1465 } else {
1466 mNetd.addSecondaryRoute(ifaceName, r);
1467 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001468 } catch (Exception e) {
1469 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08001470 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001471 return false;
1472 }
1473 } else {
1474 // if we remove this one and there are no more like it, then refcount==0 and
1475 // we can remove it from the table
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001476 if (toDefaultTable) {
1477 mAddedRoutes.remove(r);
1478 if (mAddedRoutes.contains(r) == false) {
1479 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1480 try {
1481 mNetd.removeRoute(ifaceName, r);
1482 } catch (Exception e) {
1483 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001484 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001485 return false;
1486 }
1487 } else {
1488 if (VDBG) log("not removing " + r + " as it's still in use");
1489 }
1490 } else {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001491 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001492 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001493 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001494 } catch (Exception e) {
1495 // never crash - catch them all
Robert Greenwalt2473a4ba2012-04-23 18:00:37 -07001496 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001497 return false;
1498 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001499 }
1500 }
1501 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 }
1503
1504 /**
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001505 * @see ConnectivityManager#getMobileDataEnabled()
1506 */
1507 public boolean getMobileDataEnabled() {
Wink Savillee7982682010-12-07 10:31:02 -08001508 // TODO: This detail should probably be in DataConnectionTracker's
1509 // which is where we store the value and maybe make this
1510 // asynchronous.
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001511 enforceAccessPermission();
Jeff Sharkeybdfce2e2012-09-26 15:54:06 -07001512 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1513 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001514 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001515 return retVal;
1516 }
1517
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001518 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt50393202011-06-21 17:26:14 -07001519 enforceConnectivityInternalPermission();
1520
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001521 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1522 (met ? ENABLED : DISABLED), networkType));
1523 }
1524
1525 private void handleSetDependencyMet(int networkType, boolean met) {
1526 if (mNetTrackers[networkType] != null) {
1527 if (DBG) {
1528 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1529 }
1530 mNetTrackers[networkType].setDependencyMet(met);
1531 }
1532 }
1533
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001534 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1535 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001536 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001537 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001538 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001539 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001540 }
1541
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001542 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001543 // skip update when we've already applied rules
1544 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1545 if (oldRules == uidRules) return;
1546
1547 mUidRules.put(uid, uidRules);
1548 }
1549
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001550 // TODO: notify UID when it has requested targeted updates
1551 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001552
1553 @Override
1554 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001555 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001556 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001557 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001558 }
1559
1560 synchronized (mRulesLock) {
1561 mMeteredIfaces.clear();
1562 for (String iface : meteredIfaces) {
1563 mMeteredIfaces.add(iface);
1564 }
1565 }
1566 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001567
1568 @Override
1569 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1570 // caller is NPMS, since we only register with them
1571 if (LOGD_RULES) {
1572 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1573 }
1574
1575 // kick off connectivity change broadcast for active network, since
1576 // global background policy change is radical.
1577 final int networkType = mActiveDefaultNetwork;
1578 if (isNetworkTypeValid(networkType)) {
1579 final NetworkStateTracker tracker = mNetTrackers[networkType];
1580 if (tracker != null) {
1581 final NetworkInfo info = tracker.getNetworkInfo();
1582 if (info != null && info.isConnected()) {
1583 sendConnectedBroadcast(info);
1584 }
1585 }
1586 }
1587 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001588 };
1589
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001590 /**
1591 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1592 */
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001593 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001594 enforceChangePermission();
Wink Savilleed9c02b2010-12-03 12:01:38 -08001595 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001596
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001597 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001598 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07001599 }
1600
1601 private void handleSetMobileData(boolean enabled) {
Wink Savillee7982682010-12-07 10:31:02 -08001602 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001603 if (VDBG) {
1604 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001605 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001606 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1607 }
tk.munb97d34c2012-01-06 10:43:52 +09001608 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1609 if (VDBG) {
1610 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1611 }
1612 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1613 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001614 }
1615
1616 @Override
1617 public void setPolicyDataEnable(int networkType, boolean enabled) {
1618 // only someone like NPMS should only be calling us
1619 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1620
1621 mHandler.sendMessage(mHandler.obtainMessage(
1622 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1623 }
1624
1625 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1626 if (isNetworkTypeValid(networkType)) {
1627 final NetworkStateTracker tracker = mNetTrackers[networkType];
1628 if (tracker != null) {
1629 tracker.setPolicyDataEnable(enabled);
1630 }
Robert Greenwaltc03fa502010-02-23 18:58:05 -08001631 }
1632 }
1633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001635 mContext.enforceCallingOrSelfPermission(
1636 android.Manifest.permission.ACCESS_NETWORK_STATE,
1637 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 }
1639
1640 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001641 mContext.enforceCallingOrSelfPermission(
1642 android.Manifest.permission.CHANGE_NETWORK_STATE,
1643 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08001646 // TODO Make this a special check when it goes public
1647 private void enforceTetherChangePermission() {
1648 mContext.enforceCallingOrSelfPermission(
1649 android.Manifest.permission.CHANGE_NETWORK_STATE,
1650 "ConnectivityService");
1651 }
1652
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001653 private void enforceTetherAccessPermission() {
1654 mContext.enforceCallingOrSelfPermission(
1655 android.Manifest.permission.ACCESS_NETWORK_STATE,
1656 "ConnectivityService");
1657 }
1658
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001659 private void enforceConnectivityInternalPermission() {
1660 mContext.enforceCallingOrSelfPermission(
1661 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1662 "ConnectivityService");
1663 }
1664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 /**
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001666 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1667 * network, we ignore it. If it is for the active network, we send out a
1668 * broadcast. But first, we check whether it might be possible to connect
1669 * to a different network.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 * @param info the {@code NetworkInfo} for the network
1671 */
1672 private void handleDisconnect(NetworkInfo info) {
1673
Robert Greenwalt42acef32009-08-12 16:08:25 -07001674 int prevNetType = info.getType();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675
Robert Greenwalt42acef32009-08-12 16:08:25 -07001676 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai04124232012-06-28 15:26:19 -07001677
1678 // Remove idletimer previously setup in {@code handleConnect}
1679 removeDataActivityTracking(prevNetType);
1680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 /*
1682 * If the disconnected network is not the active one, then don't report
1683 * this as a loss of connectivity. What probably happened is that we're
1684 * getting the disconnect for a network that we explicitly disabled
1685 * in accordance with network preference policies.
1686 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001687 if (!mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001688 List pids = mNetRequestersPids[prevNetType];
1689 for (int i = 0; i<pids.size(); i++) {
1690 Integer pid = (Integer)pids.get(i);
1691 // will remove them because the net's no longer connected
1692 // need to do this now as only now do we know the pids and
1693 // can properly null things that are no longer referenced.
1694 reassessPidDns(pid.intValue(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 }
1697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001699 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001700 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 if (info.isFailover()) {
1702 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1703 info.setFailover(false);
1704 }
1705 if (info.getReason() != null) {
1706 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1707 }
1708 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001709 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1710 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001712
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001713 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001714 tryFailover(prevNetType);
1715 if (mActiveDefaultNetwork != -1) {
1716 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001717 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1718 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001719 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001720 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1721 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001722 }
Robert Greenwalt029be812010-09-20 18:01:43 -07001723 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwaltec896c62011-06-15 12:22:07 -07001724
1725 // Reset interface if no other connections are using the same interface
1726 boolean doReset = true;
1727 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1728 if (linkProperties != null) {
1729 String oldIface = linkProperties.getInterfaceName();
1730 if (TextUtils.isEmpty(oldIface) == false) {
1731 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1732 if (networkStateTracker == null) continue;
1733 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1734 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1735 LinkProperties l = networkStateTracker.getLinkProperties();
1736 if (l == null) continue;
1737 if (oldIface.equals(l.getInterfaceName())) {
1738 doReset = false;
1739 break;
1740 }
1741 }
1742 }
1743 }
1744 }
1745
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001746 // do this before we broadcast the change
Robert Greenwaltec896c62011-06-15 12:22:07 -07001747 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001748
Jeff Sharkey961e3042011-08-29 16:02:57 -07001749 final Intent immediateIntent = new Intent(intent);
1750 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1751 sendStickyBroadcast(immediateIntent);
Wink Saville628b0852011-08-04 15:01:58 -07001752 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001753 /*
1754 * If the failover network is already connected, then immediately send
1755 * out a followup broadcast indicating successful failover
1756 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001757 if (mActiveDefaultNetwork != -1) {
Wink Saville628b0852011-08-04 15:01:58 -07001758 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1759 getConnectivityChangeDelay());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001760 }
1761 }
1762
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001763 private void tryFailover(int prevNetType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001764 /*
Robert Greenwaltbff90182011-01-06 15:41:07 -08001765 * If this is a default network, check if other defaults are available.
1766 * Try to reconnect on all available and let them hash it out when
1767 * more than one connects.
Robert Greenwalt42acef32009-08-12 16:08:25 -07001768 */
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001769 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001770 if (mActiveDefaultNetwork == prevNetType) {
1771 mActiveDefaultNetwork = -1;
1772 }
1773
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001774 // don't signal a reconnect for anything lower or equal priority than our
1775 // current connected default
1776 // TODO - don't filter by priority now - nice optimization but risky
1777// int currentPriority = -1;
1778// if (mActiveDefaultNetwork != -1) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001779// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001780// }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001781 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwalt5154ae762009-10-30 14:17:42 -07001782 if (checkType == prevNetType) continue;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001783 if (mNetConfigs[checkType] == null) continue;
1784 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwalt424781e2011-11-11 09:56:03 -08001785 if (mNetTrackers[checkType] == null) continue;
Wink Saville9f7a0b22011-01-26 15:43:49 -08001786
1787// Enabling the isAvailable() optimization caused mobile to not get
1788// selected if it was in the middle of error handling. Specifically
1789// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1790// would not be available and we wouldn't get connected to anything.
1791// So removing the isAvailable() optimization below for now. TODO: This
1792// optimization should work and we need to investigate why it doesn't work.
1793// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1794// complete before it is really complete.
1795// if (!mNetTrackers[checkType].isAvailable()) continue;
1796
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001797// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07001798
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001799 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1800 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1801 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1802 checkInfo.setFailover(true);
1803 checkTracker.reconnect();
Robert Greenwalt42acef32009-08-12 16:08:25 -07001804 }
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001805 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 }
1809
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001810 public void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001811 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1812 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001813 }
1814
Wink Saville628b0852011-08-04 15:01:58 -07001815 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001816 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1817 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville628b0852011-08-04 15:01:58 -07001818 }
1819
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001820 private void sendInetConditionBroadcast(NetworkInfo info) {
1821 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1822 }
1823
Wink Saville628b0852011-08-04 15:01:58 -07001824 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001825 if (mLockdownTracker != null) {
1826 info = mLockdownTracker.augmentNetworkInfo(info);
1827 }
1828
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001829 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001830 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001831 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 if (info.isFailover()) {
1833 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1834 info.setFailover(false);
1835 }
1836 if (info.getReason() != null) {
1837 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1838 }
1839 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001840 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1841 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001843 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001844 return intent;
1845 }
1846
1847 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1848 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1849 }
1850
1851 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1852 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 }
1854
Haoyu Baidb3c8672012-06-20 14:29:57 -07001855 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1856 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1857 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1858 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001859 final long ident = Binder.clearCallingIdentity();
1860 try {
1861 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1862 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1863 } finally {
1864 Binder.restoreCallingIdentity(ident);
1865 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001866 }
1867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 /**
1869 * Called when an attempt to fail over to another network has failed.
1870 * @param info the {@link NetworkInfo} for the failed network
1871 */
1872 private void handleConnectionFailure(NetworkInfo info) {
1873 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874
Robert Greenwalt42acef32009-08-12 16:08:25 -07001875 String reason = info.getReason();
1876 String extraInfo = info.getExtraInfo();
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001877
Robert Greenwalt572172b2010-10-08 16:35:52 -07001878 String reasonText;
1879 if (reason == null) {
1880 reasonText = ".";
1881 } else {
1882 reasonText = " (" + reason + ").";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08001884 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001885
1886 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001887 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001888 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt42acef32009-08-12 16:08:25 -07001889 if (getActiveNetworkInfo() == null) {
1890 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1891 }
1892 if (reason != null) {
1893 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1894 }
1895 if (extraInfo != null) {
1896 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1897 }
1898 if (info.isFailover()) {
1899 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1900 info.setFailover(false);
1901 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001902
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07001903 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001904 tryFailover(info.getType());
1905 if (mActiveDefaultNetwork != -1) {
1906 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001907 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1908 } else {
Robert Greenwalt029be812010-09-20 18:01:43 -07001909 mDefaultInetConditionPublished = 0;
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001910 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1911 }
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001912 }
Robert Greenwaltcc4b4012010-01-25 17:54:29 -08001913
Robert Greenwalt029be812010-09-20 18:01:43 -07001914 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey961e3042011-08-29 16:02:57 -07001915
1916 final Intent immediateIntent = new Intent(intent);
1917 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1918 sendStickyBroadcast(immediateIntent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001919 sendStickyBroadcast(intent);
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001920 /*
1921 * If the failover network is already connected, then immediately send
1922 * out a followup broadcast indicating successful failover
1923 */
Robert Greenwaltf21ef7d2011-01-11 13:56:33 -08001924 if (mActiveDefaultNetwork != -1) {
1925 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltda03c4e2010-01-20 19:29:41 -08001926 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001927 }
1928
1929 private void sendStickyBroadcast(Intent intent) {
1930 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001931 if (!mSystemReady) {
1932 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001933 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001934 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillec9acde92011-09-21 11:05:43 -07001935 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001936 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001937 }
1938
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001939 final long ident = Binder.clearCallingIdentity();
1940 try {
1941 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1942 } finally {
1943 Binder.restoreCallingIdentity(ident);
1944 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001945 }
1946 }
1947
Wink Saville628b0852011-08-04 15:01:58 -07001948 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1949 if (delayMs <= 0) {
1950 sendStickyBroadcast(intent);
1951 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07001952 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001953 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1954 + intent.getAction());
1955 }
Wink Saville628b0852011-08-04 15:01:58 -07001956 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1957 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1958 }
1959 }
1960
Mike Lockwood0f79b542009-08-14 14:18:49 -04001961 void systemReady() {
1962 synchronized(this) {
1963 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001964 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001965 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001966 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001967 }
1968 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001969 // load the global proxy at startup
1970 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001971
1972 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1973 // for user to unlock device.
1974 if (!updateLockdownVpn()) {
1975 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1976 mContext.registerReceiver(mUserPresentReceiver, filter);
1977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
1979
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001980 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1981 @Override
1982 public void onReceive(Context context, Intent intent) {
1983 // Try creating lockdown tracker, since user present usually means
1984 // unlocked keystore.
1985 if (updateLockdownVpn()) {
1986 mContext.unregisterReceiver(this);
1987 }
1988 }
1989 };
1990
Irfan Sheriffda6da092012-08-16 12:49:23 -07001991 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
1992 if ((type != mNetworkPreference &&
1993 mNetConfigs[mActiveDefaultNetwork].priority >
1994 mNetConfigs[type].priority) ||
1995 mNetworkPreference == mActiveDefaultNetwork) return false;
1996 return true;
1997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998
Irfan Sheriffda6da092012-08-16 12:49:23 -07001999 private void handleConnect(NetworkInfo info) {
2000 final int newNetType = info.getType();
2001
2002 setupDataActivityTracking(newNetType);
Haoyu Bai04124232012-06-28 15:26:19 -07002003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 // snapshot isFailover, because sendConnectedBroadcast() resets it
2005 boolean isFailover = info.isFailover();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002006 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002007 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008
Robert Greenwalt42acef32009-08-12 16:08:25 -07002009 // if this is a default net and other default is running
2010 // kill the one not preferred
Irfan Sheriffda6da092012-08-16 12:49:23 -07002011 if (mNetConfigs[newNetType].isDefault()) {
2012 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2013 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002014 // tear down the other
2015 NetworkStateTracker otherNet =
2016 mNetTrackers[mActiveDefaultNetwork];
Wink Savilleed9c02b2010-12-03 12:01:38 -08002017 if (DBG) {
2018 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt42acef32009-08-12 16:08:25 -07002019 " teardown");
Wink Savilleed9c02b2010-12-03 12:01:38 -08002020 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002021 if (!teardown(otherNet)) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002022 loge("Network declined teardown request");
Robert Greenwalt27725e82011-03-29 11:36:28 -07002023 teardown(thisNet);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002024 return;
2025 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002026 } else {
2027 // don't accept this one
2028 if (VDBG) {
2029 log("Not broadcasting CONNECT_ACTION " +
2030 "to torn down network " + info.getTypeName());
2031 }
2032 teardown(thisNet);
2033 return;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002034 }
2035 }
2036 synchronized (ConnectivityService.this) {
2037 // have a new default network, release the transition wakelock in a second
2038 // if it's held. The second pause is to allow apps to reconnect over the
2039 // new network
2040 if (mNetTransitionWakeLock.isHeld()) {
2041 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002042 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002043 mNetTransitionWakeLockSerialNumber, 0),
2044 1000);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002045 }
2046 }
Irfan Sheriffda6da092012-08-16 12:49:23 -07002047 mActiveDefaultNetwork = newNetType;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002048 // this will cause us to come up initially as unconnected and switching
2049 // to connected after our normal pause unless somebody reports us as reall
2050 // disconnected
2051 mDefaultInetConditionPublished = 0;
2052 mDefaultConnectionSequence++;
2053 mInetConditionChangeInFlight = false;
2054 // Don't do this - if we never sign in stay, grey
2055 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 thisNet.setTeardownRequested(false);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002058 updateNetworkSettings(thisNet);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002059 handleConnectivityChange(newNetType, false);
Wink Saville628b0852011-08-04 15:01:58 -07002060 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002061
2062 // notify battery stats service about this network
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002063 if (thisIface != null) {
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002064 try {
Irfan Sheriffda6da092012-08-16 12:49:23 -07002065 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07002066 } catch (RemoteException e) {
2067 // ignored; service lives in system_server
2068 }
2069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
2071
Irfan Sheriffda6da092012-08-16 12:49:23 -07002072 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2073 if (DBG) log("Captive portal check " + info);
2074 int type = info.getType();
2075 final NetworkStateTracker thisNet = mNetTrackers[type];
2076 if (mNetConfigs[type].isDefault()) {
2077 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2078 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2079 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07002080 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffda6da092012-08-16 12:49:23 -07002081 return;
2082 } else {
2083 if (DBG) log("Tear down low priority net " + info.getTypeName());
2084 teardown(thisNet);
2085 return;
2086 }
2087 }
2088 }
2089
2090 thisNet.captivePortalCheckComplete();
2091 }
2092
2093 /** @hide */
2094 public void captivePortalCheckComplete(NetworkInfo info) {
2095 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffda6da092012-08-16 12:49:23 -07002096 }
2097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 /**
Haoyu Bai04124232012-06-28 15:26:19 -07002099 * Setup data activity tracking for the given network interface.
2100 *
2101 * Every {@code setupDataActivityTracking} should be paired with a
2102 * {@link removeDataActivityTracking} for cleanup.
2103 */
2104 private void setupDataActivityTracking(int type) {
2105 final NetworkStateTracker thisNet = mNetTrackers[type];
2106 final String iface = thisNet.getLinkProperties().getInterfaceName();
2107
2108 final int timeout;
2109
2110 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002111 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2112 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai04124232012-06-28 15:26:19 -07002113 0);
2114 // Canonicalize mobile network type
2115 type = ConnectivityManager.TYPE_MOBILE;
2116 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002117 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2118 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07002119 0);
2120 } else {
2121 // do not track any other networks
2122 timeout = 0;
2123 }
2124
2125 if (timeout > 0 && iface != null) {
2126 try {
2127 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2128 } catch (RemoteException e) {
2129 }
2130 }
2131 }
2132
2133 /**
2134 * Remove data activity tracking when network disconnects.
2135 */
2136 private void removeDataActivityTracking(int type) {
2137 final NetworkStateTracker net = mNetTrackers[type];
2138 final String iface = net.getLinkProperties().getInterfaceName();
2139
2140 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2141 ConnectivityManager.TYPE_WIFI == type)) {
2142 try {
2143 // the call fails silently if no idletimer setup for this interface
2144 mNetd.removeIdleTimer(iface);
2145 } catch (RemoteException e) {
2146 }
2147 }
2148 }
2149
2150 /**
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002151 * After a change in the connectivity state of a network. We're mainly
2152 * concerned with making sure that the list of DNS servers is set up
2153 * according to which networks are connected, and ensuring that the
2154 * right routing table entries exist.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 */
Robert Greenwaltec896c62011-06-15 12:22:07 -07002156 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Savillee8222252011-07-13 13:44:13 -07002157 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159 /*
Robert Greenwalt42acef32009-08-12 16:08:25 -07002160 * If a non-default network is enabled, add the host routes that
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002161 * will allow it's DNS servers to be accessed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 */
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002163 handleDnsConfigurationChange(netType);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002164
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002165 LinkProperties curLp = mCurrentLinkProperties[netType];
2166 LinkProperties newLp = null;
2167
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002168 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002169 newLp = mNetTrackers[netType].getLinkProperties();
Wink Savillee8222252011-07-13 13:44:13 -07002170 if (VDBG) {
2171 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2172 " doReset=" + doReset + " resetMask=" + resetMask +
2173 "\n curLp=" + curLp +
2174 "\n newLp=" + newLp);
2175 }
2176
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002177 if (curLp != null) {
2178 if (curLp.isIdenticalInterfaceName(newLp)) {
2179 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2180 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2181 for (LinkAddress linkAddr : car.removed) {
2182 if (linkAddr.getAddress() instanceof Inet4Address) {
2183 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2184 }
2185 if (linkAddr.getAddress() instanceof Inet6Address) {
2186 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2187 }
Wink Savillee8222252011-07-13 13:44:13 -07002188 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002189 if (DBG) {
2190 log("handleConnectivityChange: addresses changed" +
2191 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2192 "\n car=" + car);
Wink Savillee8222252011-07-13 13:44:13 -07002193 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002194 } else {
2195 if (DBG) {
2196 log("handleConnectivityChange: address are the same reset per doReset" +
2197 " linkProperty[" + netType + "]:" +
2198 " resetMask=" + resetMask);
2199 }
Wink Savillee8222252011-07-13 13:44:13 -07002200 }
2201 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002202 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002203 if (DBG) {
2204 log("handleConnectivityChange: interface not not equivalent reset both" +
2205 " linkProperty[" + netType + "]:" +
2206 " resetMask=" + resetMask);
2207 }
Wink Savillee8222252011-07-13 13:44:13 -07002208 }
Wink Savillee8222252011-07-13 13:44:13 -07002209 }
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002210 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002211 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002212 }
2213 } else {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002214 if (VDBG) {
2215 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2216 " doReset=" + doReset + " resetMask=" + resetMask +
2217 "\n curLp=" + curLp +
2218 "\n newLp= null");
Robert Greenwalt42acef32009-08-12 16:08:25 -07002219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002221 mCurrentLinkProperties[netType] = newLp;
Robert Greenwaltf125a092011-08-15 12:31:55 -07002222 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwaltec896c62011-06-15 12:22:07 -07002223
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002224 if (resetMask != 0 || resetDns) {
Robert Greenwaltec896c62011-06-15 12:22:07 -07002225 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
2226 if (linkProperties != null) {
2227 String iface = linkProperties.getInterfaceName();
2228 if (TextUtils.isEmpty(iface) == false) {
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002229 if (resetMask != 0) {
Robert Greenwaltf125a092011-08-15 12:31:55 -07002230 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2231 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh0c074e62011-08-15 15:19:40 -07002232
2233 // Tell VPN the interface is down. It is a temporary
2234 // but effective fix to make VPN aware of the change.
2235 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2236 mVpn.interfaceStatusChanged(iface, false);
2237 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002238 }
2239 if (resetDns) {
Wink Savillec9acde92011-09-21 11:05:43 -07002240 if (VDBG) log("resetting DNS cache for " + iface);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002241 try {
2242 mNetd.flushInterfaceDnsCache(iface);
2243 } catch (Exception e) {
2244 // never crash - catch them all
Wink Savillec9acde92011-09-21 11:05:43 -07002245 if (DBG) loge("Exception resetting dns cache: " + e);
Robert Greenwaltf125a092011-08-15 12:31:55 -07002246 }
2247 }
Robert Greenwaltec896c62011-06-15 12:22:07 -07002248 }
2249 }
2250 }
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002251
2252 // TODO: Temporary notifying upstread change to Tethering.
2253 // @see bug/4455071
2254 /** Notify TetheringService if interface name has been changed. */
2255 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Savillea639b312012-07-10 12:37:54 -07002256 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002257 if (isTetheringSupported()) {
2258 mTethering.handleTetherIfaceChange();
2259 }
2260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 }
2262
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002263 /**
2264 * Add and remove routes using the old properties (null if not previously connected),
2265 * new properties (null if becoming disconnected). May even be double null, which
2266 * is a noop.
2267 * Uses isLinkDefault to determine if default routes should be set or conversely if
2268 * host routes should be set to the dns servers
Robert Greenwaltf125a092011-08-15 12:31:55 -07002269 * returns a boolean indicating the routes changed
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002270 */
Robert Greenwaltf125a092011-08-15 12:31:55 -07002271 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2272 boolean isLinkDefault) {
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002273 Collection<RouteInfo> routesToAdd = null;
Robert Greenwaltad55d352011-07-22 11:55:33 -07002274 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2275 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002276 if (curLp != null) {
2277 // check for the delta between the current set and the new
Robert Greenwaltad55d352011-07-22 11:55:33 -07002278 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002279 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwaltad55d352011-07-22 11:55:33 -07002280 } else if (newLp != null) {
2281 routeDiff.added = newLp.getRoutes();
2282 dnsDiff.added = newLp.getDnses();
Irfan Sheriffd649c122010-06-09 15:39:36 -07002283 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002284
Robert Greenwaltf125a092011-08-15 12:31:55 -07002285 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2286
Robert Greenwaltad55d352011-07-22 11:55:33 -07002287 for (RouteInfo r : routeDiff.removed) {
2288 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002289 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2290 }
2291 if (isLinkDefault == false) {
2292 // remove from a secondary route table
2293 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002294 }
Robert Greenwaltad55d352011-07-22 11:55:33 -07002295 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002296
Robert Greenwaltad55d352011-07-22 11:55:33 -07002297 for (RouteInfo r : routeDiff.added) {
2298 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002299 addRoute(newLp, r, TO_DEFAULT_TABLE);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002300 } else {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07002301 // add to a secondary route table
2302 addRoute(newLp, r, TO_SECONDARY_TABLE);
2303
Robert Greenwalte6b24292011-08-09 16:52:58 -07002304 // many radios add a default route even when we don't want one.
2305 // remove the default route unless somebody else has asked for it
2306 String ifaceName = newLp.getInterfaceName();
2307 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002308 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002309 try {
2310 mNetd.removeRoute(ifaceName, r);
2311 } catch (Exception e) {
2312 // never crash - catch them all
Robert Greenwalt8beff952011-12-13 15:26:02 -08002313 if (DBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte6b24292011-08-09 16:52:58 -07002314 }
2315 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002316 }
2317 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002318
Robert Greenwalt0a46db52011-07-14 14:28:05 -07002319 if (!isLinkDefault) {
2320 // handle DNS routes
Robert Greenwaltf125a092011-08-15 12:31:55 -07002321 if (routesChanged) {
Robert Greenwaltad55d352011-07-22 11:55:33 -07002322 // routes changed - remove all old dns entries and add new
2323 if (curLp != null) {
2324 for (InetAddress oldDns : curLp.getDnses()) {
2325 removeRouteToAddress(curLp, oldDns);
2326 }
2327 }
2328 if (newLp != null) {
2329 for (InetAddress newDns : newLp.getDnses()) {
2330 addRouteToAddress(newLp, newDns);
2331 }
Robert Greenwaltedcb4f92011-03-22 18:47:42 -07002332 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002333 } else {
2334 // no change in routes, check for change in dns themselves
2335 for (InetAddress oldDns : dnsDiff.removed) {
2336 removeRouteToAddress(curLp, oldDns);
2337 }
2338 for (InetAddress newDns : dnsDiff.added) {
2339 addRouteToAddress(newLp, newDns);
2340 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002341 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07002342 }
Robert Greenwaltf125a092011-08-15 12:31:55 -07002343 return routesChanged;
Irfan Sheriffd649c122010-06-09 15:39:36 -07002344 }
2345
2346
Irfan Sheriffd649c122010-06-09 15:39:36 -07002347 /**
2348 * Reads the network specific TCP buffer sizes from SystemProperties
2349 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2350 * wide use
2351 */
2352 public void updateNetworkSettings(NetworkStateTracker nt) {
2353 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey899223b2012-08-04 15:24:58 -07002354 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002355
Jeff Sharkey899223b2012-08-04 15:24:58 -07002356 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002357 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriffd649c122010-06-09 15:39:36 -07002358
2359 // Setting to default values so we won't be stuck to previous values
2360 key = "net.tcp.buffersize.default";
2361 bufferSizes = SystemProperties.get(key);
2362 }
2363
2364 // Set values in kernel
2365 if (bufferSizes.length() != 0) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002366 if (VDBG) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002367 log("Setting TCP values: [" + bufferSizes
Irfan Sheriffd649c122010-06-09 15:39:36 -07002368 + "] which comes from [" + key + "]");
2369 }
2370 setBufferSize(bufferSizes);
2371 }
2372 }
2373
2374 /**
2375 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2376 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2377 *
2378 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2379 * writeMin, writeInitial, writeMax"
2380 */
2381 private void setBufferSize(String bufferSizes) {
2382 try {
2383 String[] values = bufferSizes.split(",");
2384
2385 if (values.length == 6) {
2386 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwoodda8bb742011-05-28 13:24:04 -04002387 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2388 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2389 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2390 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2391 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2392 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002393 } else {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002394 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002395 }
2396 } catch (IOException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002397 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07002398 }
2399 }
2400
Robert Greenwalt42acef32009-08-12 16:08:25 -07002401 /**
2402 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2403 * on the highest priority active net which this process requested.
2404 * If there aren't any, clear it out
2405 */
2406 private void reassessPidDns(int myPid, boolean doBump)
2407 {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002408 if (VDBG) log("reassessPidDns for pid " + myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002409 for(int i : mPriorityList) {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002410 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002411 continue;
2412 }
2413 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002414 if (nt.getNetworkInfo().isConnected() &&
2415 !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002416 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002417 if (p == null) continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002418 List pids = mNetRequestersPids[i];
2419 for (int j=0; j<pids.size(); j++) {
2420 Integer pid = (Integer)pids.get(j);
2421 if (pid.intValue() == myPid) {
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002422 Collection<InetAddress> dnses = p.getDnses();
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002423 writePidDns(dnses, myPid);
Robert Greenwalt42acef32009-08-12 16:08:25 -07002424 if (doBump) {
2425 bumpDns();
2426 }
2427 return;
2428 }
2429 }
2430 }
2431 }
2432 // nothing found - delete
2433 for (int i = 1; ; i++) {
2434 String prop = "net.dns" + i + "." + myPid;
2435 if (SystemProperties.get(prop).length() == 0) {
2436 if (doBump) {
2437 bumpDns();
2438 }
2439 return;
2440 }
2441 SystemProperties.set(prop, "");
2442 }
2443 }
2444
Robert Greenwalt10398722010-12-17 15:20:36 -08002445 // return true if results in a change
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002446 private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002447 int j = 1;
Robert Greenwalt10398722010-12-17 15:20:36 -08002448 boolean changed = false;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07002449 for (InetAddress dns : dnses) {
Robert Greenwalt10398722010-12-17 15:20:36 -08002450 String dnsString = dns.getHostAddress();
2451 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
2452 changed = true;
yoonsung.nam7b72ea72012-03-02 19:56:16 +09002453 SystemProperties.set("net.dns" + j + "." + pid, dns.getHostAddress());
Robert Greenwalt10398722010-12-17 15:20:36 -08002454 }
yoonsung.nam7b72ea72012-03-02 19:56:16 +09002455 j++;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002456 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002457 return changed;
Robert Greenwalt42acef32009-08-12 16:08:25 -07002458 }
2459
2460 private void bumpDns() {
2461 /*
2462 * Bump the property that tells the name resolver library to reread
2463 * the DNS server list from the properties.
2464 */
2465 String propVal = SystemProperties.get("net.dnschange");
2466 int n = 0;
2467 if (propVal.length() != 0) {
2468 try {
2469 n = Integer.parseInt(propVal);
2470 } catch (NumberFormatException e) {}
2471 }
2472 SystemProperties.set("net.dnschange", "" + (n+1));
Robert Greenwalt03595d02010-11-02 14:08:23 -07002473 /*
2474 * Tell the VMs to toss their DNS caches
2475 */
2476 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2477 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08002478 /*
2479 * Connectivity events can happen before boot has completed ...
2480 */
2481 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002482 final long ident = Binder.clearCallingIdentity();
2483 try {
2484 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2485 } finally {
2486 Binder.restoreCallingIdentity(ident);
2487 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002488 }
2489
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002490 // Caller must grab mDnsLock.
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002491 private boolean updateDns(String network, String iface,
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002492 Collection<InetAddress> dnses, String domains) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002493 boolean changed = false;
2494 int last = 0;
2495 if (dnses.size() == 0 && mDefaultDns != null) {
2496 ++last;
2497 String value = mDefaultDns.getHostAddress();
2498 if (!value.equals(SystemProperties.get("net.dns1"))) {
2499 if (DBG) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002500 loge("no dns provided for " + network + " - using " + value);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002501 }
2502 changed = true;
2503 SystemProperties.set("net.dns1", value);
2504 }
2505 } else {
2506 for (InetAddress dns : dnses) {
2507 ++last;
2508 String key = "net.dns" + last;
2509 String value = dns.getHostAddress();
2510 if (!changed && value.equals(SystemProperties.get(key))) {
2511 continue;
2512 }
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002513 if (VDBG) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002514 log("adding dns " + value + " for " + network);
2515 }
2516 changed = true;
2517 SystemProperties.set(key, value);
2518 }
2519 }
2520 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2521 String key = "net.dns" + i;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002522 if (VDBG) log("erasing " + key);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002523 changed = true;
2524 SystemProperties.set(key, "");
2525 }
2526 mNumDnsEntries = last;
Robert Greenwalt8058f622012-11-09 10:52:27 -08002527 if (SystemProperties.get("net.dns.search").equals(domains) == false) {
2528 SystemProperties.set("net.dns.search", domains);
2529 changed = true;
2530 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002531
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002532 if (changed) {
2533 try {
Robert Greenwalt8058f622012-11-09 10:52:27 -08002534 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002535 mNetd.setDefaultInterfaceForDns(iface);
2536 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002537 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002538 }
2539 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002540 return changed;
2541 }
2542
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002543 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002544 // add default net's dns entries
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002545 NetworkStateTracker nt = mNetTrackers[netType];
2546 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt37e65eb2010-08-30 10:56:47 -07002547 LinkProperties p = nt.getLinkProperties();
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002548 if (p == null) return;
2549 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt10398722010-12-17 15:20:36 -08002550 boolean changed = false;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002551 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002552 String network = nt.getNetworkInfo().getTypeName();
2553 synchronized (mDnsLock) {
2554 if (!mDnsOverridden) {
Robert Greenwalt8058f622012-11-09 10:52:27 -08002555 changed = updateDns(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalte90aa5e2010-09-01 11:34:05 -07002556 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002557 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002558 } else {
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002559 try {
Robert Greenwaltc59c6da2011-07-27 10:00:36 -07002560 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt8058f622012-11-09 10:52:27 -08002561 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002562 } catch (Exception e) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08002563 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwalta10b7fd2011-07-25 16:06:25 -07002564 }
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002565 // set per-pid dns for attached secondary nets
2566 List pids = mNetRequestersPids[netType];
2567 for (int y=0; y< pids.size(); y++) {
2568 Integer pid = (Integer)pids.get(y);
Lorenzo Colittic1358b22011-09-28 22:31:45 -07002569 changed = writePidDns(dnses, pid.intValue());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 }
2571 }
Robert Greenwalt10398722010-12-17 15:20:36 -08002572 if (changed) bumpDns();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07002574 }
2575
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002576 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07002577 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2578 NETWORK_RESTORE_DELAY_PROP_NAME);
2579 if(restoreDefaultNetworkDelayStr != null &&
2580 restoreDefaultNetworkDelayStr.length() != 0) {
2581 try {
2582 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2583 } catch (NumberFormatException e) {
2584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07002586 // if the system property isn't set, use the value for the apn type
2587 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2588
2589 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2590 (mNetConfigs[networkType] != null)) {
2591 ret = mNetConfigs[networkType].restoreTime;
2592 }
2593 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 }
2595
2596 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002597 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2598 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002599 if (mContext.checkCallingOrSelfPermission(
2600 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002602 pw.println("Permission Denial: can't dump ConnectivityService " +
2603 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2604 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 return;
2606 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002607
2608 // TODO: add locking to get atomic snapshot
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002610 for (int i = 0; i < mNetTrackers.length; i++) {
2611 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwaltb9285352009-12-21 18:24:07 -08002612 if (nst != null) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002613 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2614 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002615 if (nst.getNetworkInfo().isConnected()) {
2616 pw.println("Active network: " + nst.getNetworkInfo().
2617 getTypeName());
2618 }
2619 pw.println(nst.getNetworkInfo());
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002620 pw.println(nst.getLinkProperties());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002621 pw.println(nst);
2622 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002623 pw.decreaseIndent();
Robert Greenwalt42acef32009-08-12 16:08:25 -07002624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 }
Robert Greenwaltb9285352009-12-21 18:24:07 -08002626
2627 pw.println("Network Requester Pids:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002628 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002629 for (int net : mPriorityList) {
2630 String pidString = net + ": ";
2631 for (Object pid : mNetRequestersPids[net]) {
2632 pidString = pidString + pid.toString() + ", ";
2633 }
2634 pw.println(pidString);
2635 }
2636 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002637 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002638
2639 pw.println("FeatureUsers:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002640 pw.increaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002641 for (Object requester : mFeatureUsers) {
2642 pw.println(requester.toString());
2643 }
2644 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002645 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002646
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002647 synchronized (this) {
2648 pw.println("NetworkTranstionWakeLock is currently " +
2649 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2650 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2651 }
2652 pw.println();
2653
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002654 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002655
2656 if (mInetLog != null) {
2657 pw.println();
2658 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002659 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002660 for(int i = 0; i < mInetLog.size(); i++) {
2661 pw.println(mInetLog.get(i));
2662 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002663 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 }
2666
Robert Greenwalt42acef32009-08-12 16:08:25 -07002667 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002668 private class NetworkStateTrackerHandler extends Handler {
2669 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002670 super(looper);
2671 }
2672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 @Override
2674 public void handleMessage(Message msg) {
2675 NetworkInfo info;
2676 switch (msg.what) {
2677 case NetworkStateTracker.EVENT_STATE_CHANGED:
2678 info = (NetworkInfo) msg.obj;
Robert Greenwalt511288a2009-12-07 11:33:18 -08002679 int type = info.getType();
2680 NetworkInfo.State state = info.getState();
Robert Greenwalt511288a2009-12-07 11:33:18 -08002681
Wink Savillec9acde92011-09-21 11:05:43 -07002682 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2683 (state == NetworkInfo.State.DISCONNECTED)) {
2684 log("ConnectivityChange for " +
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002685 info.getTypeName() + ": " +
Robert Greenwalt511288a2009-12-07 11:33:18 -08002686 state + "/" + info.getDetailedState());
Wink Savillec9acde92011-09-21 11:05:43 -07002687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688
Jeff Sharkey2528b502012-11-09 15:57:02 -08002689 EventLogTags.writeConnectivityStateChanged(
2690 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002691
2692 if (info.getDetailedState() ==
2693 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 handleConnectionFailure(info);
Irfan Sheriffda6da092012-08-16 12:49:23 -07002695 } else if (info.getDetailedState() ==
2696 DetailedState.CAPTIVE_PORTAL_CHECK) {
2697 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002698 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002700 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 // TODO: need to think this over.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07002702 // the logic here is, handle SUSPENDED the same as
2703 // DISCONNECTED. The only difference being we are
2704 // broadcasting an intent with NetworkInfo that's
2705 // suspended. This allows the applications an
2706 // opportunity to handle DISCONNECTED and SUSPENDED
2707 // differently, or not.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 handleDisconnect(info);
Robert Greenwalt511288a2009-12-07 11:33:18 -08002709 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 handleConnect(info);
2711 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002712 if (mLockdownTracker != null) {
2713 mLockdownTracker.onNetworkInfoChanged(info);
2714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwaltc76b8fa2010-07-23 15:46:26 -07002717 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo1ccb10e2011-06-22 21:10:34 -05002718 // TODO: Temporary allowing network configuration
2719 // change not resetting sockets.
2720 // @see bug/4455071
2721 handleConnectivityChange(info.getType(), false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 break;
Robert Greenwaltd14e1762012-08-20 11:15:39 -07002723 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2724 info = (NetworkInfo) msg.obj;
2725 type = info.getType();
2726 updateNetworkSettings(mNetTrackers[type]);
2727 break;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002728 }
2729 }
2730 }
2731
2732 private class InternalHandler extends Handler {
2733 public InternalHandler(Looper looper) {
2734 super(looper);
2735 }
2736
2737 @Override
2738 public void handleMessage(Message msg) {
2739 NetworkInfo info;
2740 switch (msg.what) {
Robert Greenwaltf3331232010-09-24 14:32:21 -07002741 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002742 String causedBy = null;
2743 synchronized (ConnectivityService.this) {
2744 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2745 mNetTransitionWakeLock.isHeld()) {
2746 mNetTransitionWakeLock.release();
2747 causedBy = mNetTransitionWakeLockCausedBy;
2748 }
2749 }
2750 if (causedBy != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002751 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002752 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002753 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002754 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07002755 FeatureUser u = (FeatureUser)msg.obj;
2756 u.expire();
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002757 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002758 case EVENT_INET_CONDITION_CHANGE:
2759 {
2760 int netType = msg.arg1;
2761 int condition = msg.arg2;
2762 handleInetConditionChange(netType, condition);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002763 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002764 }
2765 case EVENT_INET_CONDITION_HOLD_END:
2766 {
2767 int netType = msg.arg1;
2768 int sequence = msg.arg2;
2769 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002770 break;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002771 }
2772 case EVENT_SET_NETWORK_PREFERENCE:
2773 {
2774 int preference = msg.arg1;
2775 handleSetNetworkPreference(preference);
2776 break;
2777 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002778 case EVENT_SET_MOBILE_DATA:
2779 {
2780 boolean enabled = (msg.arg1 == ENABLED);
2781 handleSetMobileData(enabled);
2782 break;
2783 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002784 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2785 {
2786 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002787 break;
2788 }
2789 case EVENT_SET_DEPENDENCY_MET:
2790 {
2791 boolean met = (msg.arg1 == ENABLED);
2792 handleSetDependencyMet(msg.arg2, met);
2793 break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002794 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07002795 case EVENT_RESTORE_DNS:
2796 {
2797 if (mActiveDefaultNetwork != -1) {
2798 handleDnsConfigurationChange(mActiveDefaultNetwork);
2799 }
2800 break;
2801 }
Wink Saville628b0852011-08-04 15:01:58 -07002802 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2803 {
2804 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002805 sendStickyBroadcast(intent);
2806 break;
2807 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002808 case EVENT_SET_POLICY_DATA_ENABLE: {
2809 final int networkType = msg.arg1;
2810 final boolean enabled = msg.arg2 == ENABLED;
2811 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002812 break;
2813 }
2814 case EVENT_VPN_STATE_CHANGED: {
2815 if (mLockdownTracker != null) {
2816 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2817 }
2818 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 }
2821 }
2822 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002823
2824 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002825 public int tether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002826 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002827
2828 if (isTetheringSupported()) {
2829 return mTethering.tether(iface);
2830 } else {
2831 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2832 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002833 }
2834
2835 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002836 public int untether(String iface) {
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002837 enforceTetherChangePermission();
Robert Greenwalt5a735062010-03-02 17:25:02 -08002838
2839 if (isTetheringSupported()) {
2840 return mTethering.untether(iface);
2841 } else {
2842 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2843 }
2844 }
2845
2846 // javadoc from interface
2847 public int getLastTetherError(String iface) {
2848 enforceTetherAccessPermission();
2849
2850 if (isTetheringSupported()) {
2851 return mTethering.getLastTetherError(iface);
2852 } else {
2853 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2854 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002855 }
2856
2857 // TODO - proper iface API for selection by property, inspection, etc
2858 public String[] getTetherableUsbRegexs() {
2859 enforceTetherAccessPermission();
2860 if (isTetheringSupported()) {
2861 return mTethering.getTetherableUsbRegexs();
2862 } else {
2863 return new String[0];
2864 }
2865 }
2866
2867 public String[] getTetherableWifiRegexs() {
2868 enforceTetherAccessPermission();
2869 if (isTetheringSupported()) {
2870 return mTethering.getTetherableWifiRegexs();
2871 } else {
2872 return new String[0];
2873 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002874 }
2875
Danica Chang6fdd0c62010-08-11 14:54:43 -07002876 public String[] getTetherableBluetoothRegexs() {
2877 enforceTetherAccessPermission();
2878 if (isTetheringSupported()) {
2879 return mTethering.getTetherableBluetoothRegexs();
2880 } else {
2881 return new String[0];
2882 }
2883 }
2884
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002885 public int setUsbTethering(boolean enable) {
2886 enforceTetherAccessPermission();
2887 if (isTetheringSupported()) {
2888 return mTethering.setUsbTethering(enable);
2889 } else {
2890 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2891 }
2892 }
2893
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002894 // TODO - move iface listing, queries, etc to new module
2895 // javadoc from interface
2896 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002897 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002898 return mTethering.getTetherableIfaces();
2899 }
2900
2901 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002902 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002903 return mTethering.getTetheredIfaces();
2904 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002905
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07002906 @Override
2907 public String[] getTetheredIfacePairs() {
2908 enforceTetherAccessPermission();
2909 return mTethering.getTetheredIfacePairs();
2910 }
2911
Robert Greenwalt5a735062010-03-02 17:25:02 -08002912 public String[] getTetheringErroredIfaces() {
2913 enforceTetherAccessPermission();
2914 return mTethering.getErroredIfaces();
2915 }
2916
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002917 // if ro.tether.denied = true we default to no tethering
2918 // gservices could set the secure setting to 1 though to enable it on a build where it
2919 // had previously been turned off.
2920 public boolean isTetheringSupported() {
2921 enforceTetherAccessPermission();
2922 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002923 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2924 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -08002925 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002926 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002927
2928 // An API NetworkStateTrackers can call when they lose their network.
2929 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2930 // whichever happens first. The timer is started by the first caller and not
2931 // restarted by subsequent callers.
2932 public void requestNetworkTransitionWakelock(String forWhom) {
2933 enforceConnectivityInternalPermission();
2934 synchronized (this) {
2935 if (mNetTransitionWakeLock.isHeld()) return;
2936 mNetTransitionWakeLockSerialNumber++;
2937 mNetTransitionWakeLock.acquire();
2938 mNetTransitionWakeLockCausedBy = forWhom;
2939 }
2940 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltf3331232010-09-24 14:32:21 -07002941 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002942 mNetTransitionWakeLockSerialNumber, 0),
2943 mNetTransitionWakeLockTimeout);
2944 return;
2945 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002946
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002947 // 100 percent is full good, 0 is full bad.
2948 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002949 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002950 mContext.enforceCallingOrSelfPermission(
2951 android.Manifest.permission.STATUS_BAR,
2952 "ConnectivityService");
2953
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002954 if (DBG) {
2955 int pid = getCallingPid();
2956 int uid = getCallingUid();
2957 String s = pid + "(" + uid + ") reports inet is " +
2958 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2959 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2960 mInetLog.add(s);
2961 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2962 mInetLog.remove(0);
2963 }
2964 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002965 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002966 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2967 }
2968
2969 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002970 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07002971 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002972 return;
2973 }
2974 if (mActiveDefaultNetwork != netType) {
Wink Savillec9acde92011-09-21 11:05:43 -07002975 if (DBG) log("handleInetConditionChange: net=" + netType +
2976 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002977 return;
2978 }
Wink Savillec9acde92011-09-21 11:05:43 -07002979 if (VDBG) {
2980 log("handleInetConditionChange: net=" +
2981 netType + ", condition=" + condition +
2982 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2983 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002984 mDefaultInetCondition = condition;
2985 int delay;
2986 if (mInetConditionChangeInFlight == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07002987 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002988 // setup a new hold to debounce this
2989 if (mDefaultInetCondition > 50) {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002990 delay = Settings.Global.getInt(mContext.getContentResolver(),
2991 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002992 } else {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002993 delay = Settings.Global.getInt(mContext.getContentResolver(),
2994 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002995 }
2996 mInetConditionChangeInFlight = true;
2997 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2998 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2999 } else {
Wink Savillec9acde92011-09-21 11:05:43 -07003000 // we've set the new condition, when this hold ends that will get picked up
3001 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003002 }
3003 }
3004
3005 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003006 if (DBG) {
3007 log("handleInetConditionHoldEnd: net=" + netType +
3008 ", condition=" + mDefaultInetCondition +
3009 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003010 }
3011 mInetConditionChangeInFlight = false;
3012
3013 if (mActiveDefaultNetwork == -1) {
Wink Savillec9acde92011-09-21 11:05:43 -07003014 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003015 return;
3016 }
3017 if (mDefaultConnectionSequence != sequence) {
Wink Savillec9acde92011-09-21 11:05:43 -07003018 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003019 return;
3020 }
Wink Saville628b0852011-08-04 15:01:58 -07003021 // TODO: Figure out why this optimization sometimes causes a
3022 // change in mDefaultInetCondition to be missed and the
3023 // UI to not be updated.
3024 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3025 // if (DBG) log("no change in condition - aborting");
3026 // return;
3027 //}
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003028 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3029 if (networkInfo.isConnected() == false) {
Wink Savillec9acde92011-09-21 11:05:43 -07003030 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003031 return;
3032 }
3033 mDefaultInetConditionPublished = mDefaultInetCondition;
3034 sendInetConditionBroadcast(networkInfo);
3035 return;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003036 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003037
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003038 public ProxyProperties getProxy() {
3039 synchronized (mDefaultProxyLock) {
3040 return mDefaultProxyDisabled ? null : mDefaultProxy;
3041 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003042 }
3043
3044 public void setGlobalProxy(ProxyProperties proxyProperties) {
3045 enforceChangePermission();
3046 synchronized (mGlobalProxyLock) {
3047 if (proxyProperties == mGlobalProxy) return;
3048 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3049 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3050
3051 String host = "";
3052 int port = 0;
3053 String exclList = "";
3054 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3055 mGlobalProxy = new ProxyProperties(proxyProperties);
3056 host = mGlobalProxy.getHost();
3057 port = mGlobalProxy.getPort();
3058 exclList = mGlobalProxy.getExclusionList();
3059 } else {
3060 mGlobalProxy = null;
3061 }
3062 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003063 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3064 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3065 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
Robert Greenwalt434203a2010-10-11 16:00:27 -07003066 exclList);
3067 }
3068
3069 if (mGlobalProxy == null) {
3070 proxyProperties = mDefaultProxy;
3071 }
Chia-chi Yehe4474c32011-09-28 16:38:18 -07003072 //sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003073 }
3074
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003075 private void loadGlobalProxy() {
3076 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003077 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3078 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3079 String exclList = Settings.Global.getString(res,
3080 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003081 if (!TextUtils.isEmpty(host)) {
3082 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
3083 synchronized (mGlobalProxyLock) {
3084 mGlobalProxy = proxyProperties;
3085 }
3086 }
3087 }
3088
Robert Greenwalt434203a2010-10-11 16:00:27 -07003089 public ProxyProperties getGlobalProxy() {
3090 synchronized (mGlobalProxyLock) {
3091 return mGlobalProxy;
3092 }
3093 }
3094
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003095 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3096 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3097 proxy = null;
3098 }
3099 synchronized (mDefaultProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003100 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3101 if (mDefaultProxy == proxy) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003102 mDefaultProxy = proxy;
3103
3104 if (!mDefaultProxyDisabled) {
3105 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003106 }
3107 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003108 }
3109
3110 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003111 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3112 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003113 if (!TextUtils.isEmpty(proxy)) {
3114 String data[] = proxy.split(":");
3115 String proxyHost = data[0];
3116 int proxyPort = 8080;
3117 if (data.length > 1) {
3118 try {
3119 proxyPort = Integer.parseInt(data[1]);
3120 } catch (NumberFormatException e) {
3121 return;
3122 }
3123 }
3124 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3125 setGlobalProxy(p);
3126 }
3127 }
3128
3129 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt55985be2010-12-23 15:51:10 -08003130 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003131 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003132 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003133 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3134 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003135 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003136 final long ident = Binder.clearCallingIdentity();
3137 try {
3138 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3139 } finally {
3140 Binder.restoreCallingIdentity(ident);
3141 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003142 }
3143
3144 private static class SettingsObserver extends ContentObserver {
3145 private int mWhat;
3146 private Handler mHandler;
3147 SettingsObserver(Handler handler, int what) {
3148 super(handler);
3149 mHandler = handler;
3150 mWhat = what;
3151 }
3152
3153 void observe(Context context) {
3154 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003155 resolver.registerContentObserver(Settings.Global.getUriFor(
3156 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003157 }
3158
3159 @Override
3160 public void onChange(boolean selfChange) {
3161 mHandler.obtainMessage(mWhat).sendToTarget();
3162 }
3163 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003164
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003165 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003166 Slog.d(TAG, s);
3167 }
3168
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003169 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003170 Slog.e(TAG, s);
3171 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003172
repo syncaea743a2011-07-29 23:55:49 -07003173 int convertFeatureToNetworkType(int networkType, String feature) {
3174 int usedNetworkType = networkType;
3175
3176 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3177 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3178 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3179 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3180 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3181 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3182 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3183 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3184 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3185 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3186 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3187 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3188 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3189 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3190 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3191 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3192 } else {
3193 Slog.e(TAG, "Can't match any mobile netTracker!");
3194 }
3195 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3196 if (TextUtils.equals(feature, "p2p")) {
3197 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3198 } else {
3199 Slog.e(TAG, "Can't match any wifi netTracker!");
3200 }
3201 } else {
3202 Slog.e(TAG, "Unexpected network type");
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003203 }
repo syncaea743a2011-07-29 23:55:49 -07003204 return usedNetworkType;
Wink Saville2b8bcfe2011-02-24 17:58:51 -08003205 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003206
3207 private static <T> T checkNotNull(T value, String message) {
3208 if (value == null) {
3209 throw new NullPointerException(message);
3210 }
3211 return value;
3212 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003213
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003214 /**
3215 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003216 * VpnBuilder and not available in ConnectivityManager. Permissions
3217 * are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003218 * @hide
3219 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003220 @Override
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003221 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003222 throwIfLockdownEnabled();
Chia-chi Yeh5779c9c2011-07-14 16:19:19 -07003223 try {
3224 int type = mActiveDefaultNetwork;
3225 if (ConnectivityManager.isNetworkTypeValid(type)) {
3226 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3227 return true;
3228 }
3229 } catch (Exception e) {
3230 // ignore
3231 } finally {
3232 try {
3233 socket.close();
3234 } catch (Exception e) {
3235 // ignore
3236 }
3237 }
3238 return false;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003239 }
3240
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003241 /**
3242 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003243 * and not available in ConnectivityManager. Permissions are checked
3244 * in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003245 * @hide
3246 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003247 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003248 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003249 throwIfLockdownEnabled();
Chia-chi Yeh100155a2011-07-03 16:52:38 -07003250 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003251 }
3252
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003253 /**
3254 * Configure a TUN interface and return its file descriptor. Parameters
3255 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003256 * and not available in ConnectivityManager. Permissions are checked in
3257 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003258 * @hide
3259 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003260 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003261 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003262 throwIfLockdownEnabled();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003263 return mVpn.establish(config);
3264 }
3265
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003266 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003267 * Start legacy VPN, controlling native daemons as needed. Creates a
3268 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003269 */
3270 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003271 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003272 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003273 final LinkProperties egress = getActiveLinkProperties();
3274 if (egress == null) {
3275 throw new IllegalStateException("Missing active network connection");
3276 }
3277 mVpn.startLegacyVpn(profile, mKeyStore, egress);
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003278 }
3279
3280 /**
3281 * Return the information of the ongoing legacy VPN. This method is used
3282 * by VpnSettings and not available in ConnectivityManager. Permissions
3283 * are checked in Vpn class.
3284 * @hide
3285 */
3286 @Override
3287 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003288 throwIfLockdownEnabled();
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003289 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003290 }
3291
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003292 /**
3293 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3294 * through NetworkStateTracker since it works differently. For example, it
3295 * needs to override DNS servers but never takes the default routes. It
3296 * relies on another data network, and it could keep existing connections
3297 * alive after reconnecting, switching between networks, or even resuming
3298 * from deep sleep. Calls from applications should be done synchronously
3299 * to avoid race conditions. As these are all hidden APIs, refactoring can
3300 * be done whenever a better abstraction is developed.
3301 */
3302 public class VpnCallback {
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003303 private VpnCallback() {
3304 }
3305
Jeff Sharkey899223b2012-08-04 15:24:58 -07003306 public void onStateChanged(NetworkInfo info) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003307 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey899223b2012-08-04 15:24:58 -07003308 }
3309
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003310 public void override(List<String> dnsServers, List<String> searchDomains) {
3311 if (dnsServers == null) {
3312 restore();
3313 return;
3314 }
3315
3316 // Convert DNS servers into addresses.
3317 List<InetAddress> addresses = new ArrayList<InetAddress>();
3318 for (String address : dnsServers) {
3319 // Double check the addresses and remove invalid ones.
3320 try {
3321 addresses.add(InetAddress.parseNumericAddress(address));
3322 } catch (Exception e) {
3323 // ignore
3324 }
3325 }
3326 if (addresses.isEmpty()) {
3327 restore();
3328 return;
3329 }
3330
3331 // Concatenate search domains into a string.
3332 StringBuilder buffer = new StringBuilder();
3333 if (searchDomains != null) {
3334 for (String domain : searchDomains) {
3335 buffer.append(domain).append(' ');
3336 }
3337 }
3338 String domains = buffer.toString().trim();
3339
3340 // Apply DNS changes.
3341 boolean changed = false;
3342 synchronized (mDnsLock) {
Lorenzo Colittic1358b22011-09-28 22:31:45 -07003343 changed = updateDns("VPN", "VPN", addresses, domains);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003344 mDnsOverridden = true;
3345 }
3346 if (changed) {
3347 bumpDns();
3348 }
3349
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003350 // Temporarily disable the default proxy.
3351 synchronized (mDefaultProxyLock) {
3352 mDefaultProxyDisabled = true;
3353 if (mDefaultProxy != null) {
3354 sendProxyBroadcast(null);
3355 }
3356 }
3357
3358 // TODO: support proxy per network.
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003359 }
3360
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003361 public void restore() {
3362 synchronized (mDnsLock) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003363 if (mDnsOverridden) {
3364 mDnsOverridden = false;
3365 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003366 }
Chia-chi Yeh44bb2512011-07-14 18:01:57 -07003367 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003368 synchronized (mDefaultProxyLock) {
3369 mDefaultProxyDisabled = false;
3370 if (mDefaultProxy != null) {
3371 sendProxyBroadcast(mDefaultProxy);
3372 }
3373 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003374 }
3375 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003376
3377 @Override
3378 public boolean updateLockdownVpn() {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07003379 enforceSystemUid();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003380
3381 // Tear down existing lockdown if profile was removed
3382 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3383 if (mLockdownEnabled) {
3384 if (mKeyStore.state() != KeyStore.State.UNLOCKED) {
3385 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3386 return false;
3387 }
3388
3389 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3390 final VpnProfile profile = VpnProfile.decode(
3391 profileName, mKeyStore.get(Credentials.VPN + profileName));
3392 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3393 } else {
3394 setLockdownTracker(null);
3395 }
3396
3397 return true;
3398 }
3399
3400 /**
3401 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3402 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3403 */
3404 private void setLockdownTracker(LockdownVpnTracker tracker) {
3405 // Shutdown any existing tracker
3406 final LockdownVpnTracker existing = mLockdownTracker;
3407 mLockdownTracker = null;
3408 if (existing != null) {
3409 existing.shutdown();
3410 }
3411
3412 try {
3413 if (tracker != null) {
3414 mNetd.setFirewallEnabled(true);
3415 mLockdownTracker = tracker;
3416 mLockdownTracker.init();
3417 } else {
3418 mNetd.setFirewallEnabled(false);
3419 }
3420 } catch (RemoteException e) {
3421 // ignored; NMS lives inside system_server
3422 }
3423 }
3424
3425 private void throwIfLockdownEnabled() {
3426 if (mLockdownEnabled) {
3427 throw new IllegalStateException("Unavailable in lockdown mode");
3428 }
3429 }
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07003430
3431 private static void enforceSystemUid() {
3432 final int uid = Binder.getCallingUid();
3433 if (uid != Process.SYSTEM_UID) {
3434 throw new SecurityException("Only available to AID_SYSTEM");
3435 }
3436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437}