blob: 9e9253a0f303ed138f5539d7ee40b667edc3440d [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4434b0b2011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baib5da5752012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070023import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
24import static android.net.ConnectivityManager.TYPE_DUMMY;
25import static android.net.ConnectivityManager.TYPE_ETHERNET;
26import static android.net.ConnectivityManager.TYPE_MOBILE;
27import static android.net.ConnectivityManager.TYPE_WIFI;
28import static android.net.ConnectivityManager.TYPE_WIMAX;
29import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070030import static android.net.ConnectivityManager.isNetworkTypeValid;
31import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070033
Wink Saville32506bc2013-06-29 21:10:57 -070034import android.app.Notification;
35import android.app.NotificationManager;
36import android.app.PendingIntent;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080037import android.bluetooth.BluetoothTetheringDataTracker;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070038import android.content.BroadcastReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080039import android.content.ContentResolver;
40import android.content.Context;
tk.mun093f55c2011-10-13 22:51:57 +090041import android.content.ContextWrapper;
The Android Open Source Project28527d22009-03-03 19:31:44 -080042import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project28527d22009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
tk.mun093f55c2011-10-13 22:51:57 +090045import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070046import android.database.ContentObserver;
Irfan Sheriff0ad0d132012-08-16 12:49:23 -070047import android.net.CaptivePortalTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080048import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080049import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080050import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070056import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080057import android.net.LinkProperties;
Wink Saville32506bc2013-06-29 21:10:57 -070058import android.net.Uri;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070059import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080060import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070061import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080062import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070063import android.net.NetworkInfo.DetailedState;
Wink Saville32506bc2013-06-29 21:10:57 -070064import android.net.NetworkInfo.State;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070065import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070066import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080067import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070068import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070069import android.net.Proxy;
70import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070071import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080072import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090073import android.net.wimax.WimaxManagerConstants;
Wink Saville32506bc2013-06-29 21:10:57 -070074import android.os.AsyncTask;
The Android Open Source Project28527d22009-03-03 19:31:44 -080075import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040076import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080077import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070078import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070079import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070080import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080081import android.os.Looper;
82import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -070083import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070084import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070085import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -070086import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070087import android.os.RemoteException;
Wink Saville32506bc2013-06-29 21:10:57 -070088import android.os.ResultReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080089import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070090import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080091import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -070092import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080093import android.provider.Settings;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -070094import android.security.Credentials;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -070095import android.security.KeyStore;
Wink Saville32506bc2013-06-29 21:10:57 -070096import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070097import android.text.TextUtils;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080098import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070099import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800100
Wink Saville32506bc2013-06-29 21:10:57 -0700101import com.android.internal.R;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700102import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700103import com.android.internal.net.VpnConfig;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700104import com.android.internal.net.VpnProfile;
Wink Saville32506bc2013-06-29 21:10:57 -0700105import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700106import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700107import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700108import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700109import com.android.server.am.BatteryStatsService;
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900110import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800111import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700112import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700113import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700114import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700115import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700116import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700117
tk.mun093f55c2011-10-13 22:51:57 +0900118import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700119
The Android Open Source Project28527d22009-03-03 19:31:44 -0800120import java.io.FileDescriptor;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700121import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800122import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900123import java.lang.reflect.Constructor;
Wink Saville32506bc2013-06-29 21:10:57 -0700124import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700125import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700126import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700127import java.net.InetAddress;
Wink Saville32506bc2013-06-29 21:10:57 -0700128import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700129import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700130import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700131import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700132import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700133import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700134import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700135import java.util.List;
Wink Saville32506bc2013-06-29 21:10:57 -0700136import java.util.Random;
137import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800138
139/**
140 * @hide
141 */
142public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700143 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800144
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700145 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700146 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800147
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700148 private static final boolean LOGD_RULES = false;
149
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700150 // TODO: create better separation between radio types and network types
151
Robert Greenwalt2034b912009-08-12 16:08:25 -0700152 // how long to wait before switching back to a radio's default network
153 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
154 // system property that can override the above value
155 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
156 "android.telephony.apn-restore";
157
Wink Saville32506bc2013-06-29 21:10:57 -0700158 // Default value if FAIL_FAST_TIME_MS is not set
159 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
160 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
161 private static final String FAIL_FAST_TIME_MS =
162 "persist.radio.fail_fast_time_ms";
163
Robert Greenwaltbd492212011-05-06 17:10:53 -0700164 // used in recursive route setting to add gateways for the host for which
165 // a host route was requested.
166 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
167
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800168 private Tethering mTethering;
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800169 private boolean mTetheringConfigValid = false;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800170
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700171 private KeyStore mKeyStore;
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700172
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700173 private Vpn mVpn;
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700174 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700175
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700176 private boolean mLockdownEnabled;
177 private LockdownVpnTracker mLockdownTracker;
178
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900179 private Nat464Xlat mClat;
180
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700181 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
182 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700183 /** Currently active network rules by UID. */
184 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700185 /** Set of ifaces that are costly. */
186 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700187
The Android Open Source Project28527d22009-03-03 19:31:44 -0800188 /**
189 * Sometimes we want to refer to the individual network state
190 * trackers separately, and sometimes we just want to treat them
191 * abstractly.
192 */
193 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700194
Irfan Sheriff0ad0d132012-08-16 12:49:23 -0700195 /* Handles captive portal check on a network */
196 private CaptivePortalTracker mCaptivePortalTracker;
197
Robert Greenwalt2034b912009-08-12 16:08:25 -0700198 /**
Wink Saville051a6642011-07-13 13:44:13 -0700199 * The link properties that define the current links
200 */
201 private LinkProperties mCurrentLinkProperties[];
202
203 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700204 * A per Net list of the PID's that requested access to the net
205 * used both as a refcount and for per-PID DNS selection
206 */
Mattias Falkd697aa22011-08-23 14:15:13 +0200207 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700208
Robert Greenwalt2034b912009-08-12 16:08:25 -0700209 // priority order of the nettrackers
210 // (excluding dynamically set mNetworkPreference)
211 // TODO - move mNetworkTypePreference into this
212 private int[] mPriorityList;
213
The Android Open Source Project28527d22009-03-03 19:31:44 -0800214 private Context mContext;
215 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700216 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700217 // 0 is full bad, 100 is full good
Wink Saville151eaa62013-01-31 00:30:13 +0000218 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700219 private int mDefaultInetConditionPublished = 0;
220 private boolean mInetConditionChangeInFlight = false;
221 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222
Chia-chi Yehcc844502011-07-14 18:01:57 -0700223 private Object mDnsLock = new Object();
Robert Greenwalte41e3b32013-02-11 15:25:10 -0800224 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700225 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800226
227 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700228 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229
Robert Greenwalt355205c2011-05-10 15:05:02 -0700230 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700231 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700232
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700233 private static final int ENABLED = 1;
234 private static final int DISABLED = 0;
235
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700236 private static final boolean ADD = true;
237 private static final boolean REMOVE = false;
238
239 private static final boolean TO_DEFAULT_TABLE = true;
240 private static final boolean TO_SECONDARY_TABLE = false;
241
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700242 /**
243 * used internally as a delayed event to make us switch back to the
244 * default network
245 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700246 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700247
248 /**
249 * used internally to change our mobile data enabled flag
250 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700251 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700252
253 /**
254 * used internally to change our network preference setting
255 * arg1 = networkType to prefer
256 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700257 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700258
259 /**
260 * used internally to synchronize inet condition reports
261 * arg1 = networkType
262 * arg2 = condition (0 bad, 100 good)
263 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700264 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700265
266 /**
267 * used internally to mark the end of inet condition hold periods
268 * arg1 = networkType
269 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700270 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700271
272 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700273 * used internally to set enable/disable cellular data
274 * arg1 = ENBALED or DISABLED
275 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700276 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700277
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700278 /**
279 * used internally to clear a wakelock when transitioning
280 * from one net to another
281 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700282 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700283
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700284 /**
285 * used internally to reload global proxy settings
286 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700287 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700288
Robert Greenwalt34848c02011-03-25 13:09:25 -0700289 /**
290 * used internally to set external dependency met/unmet
291 * arg1 = ENABLED (met) or DISABLED (unmet)
292 * arg2 = NetworkType
293 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700294 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700295
Chia-chi Yehcc844502011-07-14 18:01:57 -0700296 /**
297 * used internally to restore DNS properties back to the
298 * default network
299 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700300 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700301
Wink Saville7e4333c2011-08-05 11:40:22 -0700302 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700303 * used internally to send a sticky broadcast delayed.
304 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700305 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700306
Jeff Sharkey805662d2011-08-19 02:24:24 -0700307 /**
308 * Used internally to
309 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
310 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700311 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700312
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700313 private static final int EVENT_VPN_STATE_CHANGED = 14;
314
Wink Saville32506bc2013-06-29 21:10:57 -0700315 /**
316 * Used internally to disable fail fast of mobile data
317 */
318 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 15;
319
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700320 /** Handler used for internal events. */
321 private InternalHandler mHandler;
322 /** Handler used for incoming {@link NetworkStateTracker} events. */
323 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700324
325 // list of DeathRecipients used to make sure features are turned off when
326 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500327 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700328
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400329 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800330 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400331
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700332 private PowerManager.WakeLock mNetTransitionWakeLock;
333 private String mNetTransitionWakeLockCausedBy = "";
334 private int mNetTransitionWakeLockSerialNumber;
335 private int mNetTransitionWakeLockTimeout;
336
Robert Greenwalt94daa182010-09-01 11:34:05 -0700337 private InetAddress mDefaultDns;
338
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700339 // this collection is used to refcount the added routes - if there are none left
340 // it's time to remove the route from the route table
341 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
342
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700343 // used in DBG mode to track inet condition reports
344 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
345 private ArrayList mInetLog;
346
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700347 // track the current default http proxy - tell the world if we get a new one (real change)
348 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltf9661d32013-04-05 17:14:19 -0700349 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700350 private boolean mDefaultProxyDisabled = false;
351
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700352 // track the global proxy.
353 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700354
355 private SettingsObserver mSettingsObserver;
356
Robert Greenwalt34848c02011-03-25 13:09:25 -0700357 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700358 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700359
Robert Greenwalt12c44552009-12-07 11:33:18 -0800360 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700361 public int mSimultaneity;
362 public int mType;
363 public RadioAttributes(String init) {
364 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700365 mType = Integer.parseInt(fragments[0]);
366 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700367 }
368 }
369 RadioAttributes[] mRadioAttributes;
370
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700371 // the set of network types that can only be enabled by system/sig apps
372 List mProtectedNetworks;
373
Wink Saville32506bc2013-06-29 21:10:57 -0700374 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
375
376 TelephonyManager mTelephonyManager;
377
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700378 public ConnectivityService(Context context, INetworkManagementService netd,
379 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700380 // Currently, omitting a NetworkFactory will create one internally
381 // TODO: create here when we have cleaner WiMAX support
382 this(context, netd, statsService, policyManager, null);
383 }
384
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700385 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700386 INetworkStatsService statsService, INetworkPolicyManager policyManager,
387 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800388 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800389
Wink Saville775aad62010-09-02 19:23:52 -0700390 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
391 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700392 mHandler = new InternalHandler(handlerThread.getLooper());
393 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700394
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700395 if (netFactory == null) {
396 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
397 }
398
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800399 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800400 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
401 String id = Settings.Secure.getString(context.getContentResolver(),
402 Settings.Secure.ANDROID_ID);
403 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700404 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800405 SystemProperties.set("net.hostname", name);
406 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800407 }
408
Robert Greenwalt94daa182010-09-01 11:34:05 -0700409 // read our default dns server ip
Jeff Sharkey8c870452012-09-26 22:03:49 -0700410 String dns = Settings.Global.getString(context.getContentResolver(),
411 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700412 if (dns == null || dns.length() == 0) {
413 dns = context.getResources().getString(
414 com.android.internal.R.string.config_default_dns_server);
415 }
416 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800417 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
418 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800419 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700420 }
421
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700422 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700423 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700424 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -0700425 mKeyStore = KeyStore.getInstance();
Wink Saville32506bc2013-06-29 21:10:57 -0700426 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700427
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700428 try {
429 mPolicyManager.registerListener(mPolicyListener);
430 } catch (RemoteException e) {
431 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700432 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700433 }
434
435 final PowerManager powerManager = (PowerManager) context.getSystemService(
436 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700437 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
438 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
439 com.android.internal.R.integer.config_networkTransitionTimeout);
440
Robert Greenwalt2034b912009-08-12 16:08:25 -0700441 mNetTrackers = new NetworkStateTracker[
442 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700443 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700444
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700445 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700446 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700447
Robert Greenwalt2034b912009-08-12 16:08:25 -0700448 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700449 String[] raStrings = context.getResources().getStringArray(
450 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700451 for (String raString : raStrings) {
452 RadioAttributes r = new RadioAttributes(raString);
453 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800454 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700455 continue;
456 }
457 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800458 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700459 r.mType);
460 continue;
461 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700462 mRadioAttributes[r.mType] = r;
463 }
464
Wink Saville00fe5092013-04-23 14:26:51 -0700465 // TODO: What is the "correct" way to do determine if this is a wifi only device?
466 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
467 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700468 String[] naStrings = context.getResources().getStringArray(
469 com.android.internal.R.array.networkAttributes);
470 for (String naString : naStrings) {
471 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700472 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700473 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800474 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700475 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700476 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700477 }
Wink Saville00fe5092013-04-23 14:26:51 -0700478 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
479 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
480 n.type);
481 continue;
482 }
Wink Savillef2a62832011-04-07 14:23:45 -0700483 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800484 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700485 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700486 continue;
487 }
Wink Savillef2a62832011-04-07 14:23:45 -0700488 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800489 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700490 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700491 continue;
492 }
Wink Savillef2a62832011-04-07 14:23:45 -0700493 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700494 mNetworksDefined++;
495 } catch(Exception e) {
496 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700497 }
498 }
499
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700500 mProtectedNetworks = new ArrayList<Integer>();
501 int[] protectedNetworks = context.getResources().getIntArray(
502 com.android.internal.R.array.config_protectedNetworks);
503 for (int p : protectedNetworks) {
504 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
505 mProtectedNetworks.add(p);
506 } else {
507 if (DBG) loge("Ignoring protectedNetwork " + p);
508 }
509 }
510
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700511 // high priority first
512 mPriorityList = new int[mNetworksDefined];
513 {
514 int insertionPoint = mNetworksDefined-1;
515 int currentLowest = 0;
516 int nextLowest = 0;
517 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700518 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700519 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700520 if (na.priority < currentLowest) continue;
521 if (na.priority > currentLowest) {
522 if (na.priority < nextLowest || nextLowest == 0) {
523 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700524 }
525 continue;
526 }
Wink Savillef2a62832011-04-07 14:23:45 -0700527 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700528 }
529 currentLowest = nextLowest;
530 nextLowest = 0;
531 }
532 }
533
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800534 // Update mNetworkPreference according to user mannually first then overlay config.xml
535 mNetworkPreference = getPersistedNetworkPreference();
536 if (mNetworkPreference == -1) {
537 for (int n : mPriorityList) {
538 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
539 mNetworkPreference = n;
540 break;
541 }
542 }
543 if (mNetworkPreference == -1) {
544 throw new IllegalStateException(
545 "You should set at least one default Network in config.xml!");
546 }
547 }
548
Mattias Falkd697aa22011-08-23 14:15:13 +0200549 mNetRequestersPids =
550 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700551 for (int i : mPriorityList) {
Mattias Falkd697aa22011-08-23 14:15:13 +0200552 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700553 }
554
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500555 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700556
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700557 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
558 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700559
560 // Create and start trackers for hard-coded networks
561 for (int targetNetworkType : mPriorityList) {
562 final NetworkConfig config = mNetConfigs[targetNetworkType];
563 final NetworkStateTracker tracker;
564 try {
565 tracker = netFactory.createTracker(targetNetworkType, config);
566 mNetTrackers[targetNetworkType] = tracker;
567 } catch (IllegalArgumentException e) {
568 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
569 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700570 continue;
571 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700572
573 tracker.startMonitoring(context, mTrackerHandler);
574 if (config.isDefault()) {
575 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800576 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700577 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800578
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700579 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700580 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
Danica Chang96567052010-08-11 14:54:43 -0700581 mTethering.getTetherableWifiRegexs().length != 0 ||
582 mTethering.getTetherableBluetoothRegexs().length != 0) &&
Robert Greenwalt33cdcdf2011-06-02 17:30:47 -0700583 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800584
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -0700585 mVpn = new Vpn(mContext, mVpnCallback, mNetd, this);
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700586 mVpn.startMonitoring(mContext, mTrackerHandler);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700587
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900588 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
589
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700590 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700591 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700592 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +0900593 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700594 } catch (RemoteException e) {
595 loge("Error registering observer :" + e);
596 }
597
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700598 if (DBG) {
599 mInetLog = new ArrayList();
600 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700601
602 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
603 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800604
Irfan Sheriff32bed2c2012-09-20 09:32:41 -0700605 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800606 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800607 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700608
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700609 /**
610 * Factory that creates {@link NetworkStateTracker} instances using given
611 * {@link NetworkConfig}.
612 */
613 public interface NetworkFactory {
614 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
615 }
616
617 private static class DefaultNetworkFactory implements NetworkFactory {
618 private final Context mContext;
619 private final Handler mTrackerHandler;
620
621 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
622 mContext = context;
623 mTrackerHandler = trackerHandler;
624 }
625
626 @Override
627 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
628 switch (config.radio) {
629 case TYPE_WIFI:
630 return new WifiStateTracker(targetNetworkType, config.name);
631 case TYPE_MOBILE:
632 return new MobileDataStateTracker(targetNetworkType, config.name);
633 case TYPE_DUMMY:
634 return new DummyDataStateTracker(targetNetworkType, config.name);
635 case TYPE_BLUETOOTH:
636 return BluetoothTetheringDataTracker.getInstance();
637 case TYPE_WIMAX:
638 return makeWimaxStateTracker(mContext, mTrackerHandler);
639 case TYPE_ETHERNET:
640 return EthernetDataTracker.getInstance();
641 default:
642 throw new IllegalArgumentException(
643 "Trying to create a NetworkStateTracker for an unknown radio type: "
644 + config.radio);
645 }
646 }
647 }
648
649 /**
650 * Loads external WiMAX library and registers as system service, returning a
651 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
652 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
653 */
654 private static NetworkStateTracker makeWimaxStateTracker(
655 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700656 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900657 DexClassLoader wimaxClassLoader;
658 Class wimaxStateTrackerClass = null;
659 Class wimaxServiceClass = null;
660 Class wimaxManagerClass;
661 String wimaxJarLocation;
662 String wimaxLibLocation;
663 String wimaxManagerClassName;
664 String wimaxServiceClassName;
665 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800666
tk.mun093f55c2011-10-13 22:51:57 +0900667 NetworkStateTracker wimaxStateTracker = null;
668
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700669 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900670 com.android.internal.R.bool.config_wimaxEnabled);
671
672 if (isWimaxEnabled) {
673 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700674 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900675 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700676 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900677 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700678 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900679 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700680 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900681 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700682 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900683 com.android.internal.R.string.config_wimaxStateTrackerClassname);
684
Dianne Hackborndc456a62012-11-08 11:12:09 -0800685 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900686 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700687 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900688 wimaxLibLocation, ClassLoader.getSystemClassLoader());
689
690 try {
691 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
692 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
693 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
694 } catch (ClassNotFoundException ex) {
695 loge("Exception finding Wimax classes: " + ex.toString());
696 return null;
697 }
698 } catch(Resources.NotFoundException ex) {
699 loge("Wimax Resources does not exist!!! ");
700 return null;
701 }
702
703 try {
Dianne Hackborndc456a62012-11-08 11:12:09 -0800704 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900705
706 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
707 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700708 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
709 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900710
711 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
712 (new Class[] {Context.class, wimaxStateTrackerClass});
713 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700714 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900715 wmxSrvConst.setAccessible(false);
716
717 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
718
719 } catch(Exception ex) {
720 loge("Exception creating Wimax classes: " + ex.toString());
721 return null;
722 }
723 } else {
724 loge("Wimax is not enabled or not added to the network attributes!!! ");
725 return null;
726 }
727
728 return wimaxStateTracker;
729 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700730
The Android Open Source Project28527d22009-03-03 19:31:44 -0800731 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700732 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800733 * @param preference the new preference
734 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700735 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800736 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700737
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700738 mHandler.sendMessage(
739 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800740 }
741
742 public int getNetworkPreference() {
743 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700744 int preference;
745 synchronized(this) {
746 preference = mNetworkPreference;
747 }
748 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800749 }
750
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700751 private void handleSetNetworkPreference(int preference) {
752 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700753 mNetConfigs[preference] != null &&
754 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700755 if (mNetworkPreference != preference) {
756 final ContentResolver cr = mContext.getContentResolver();
Jeff Brownc67cf562012-09-25 15:03:20 -0700757 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700758 synchronized(this) {
759 mNetworkPreference = preference;
760 }
761 enforcePreference();
762 }
763 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800764 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700765
Wink Saville4f0de1e2011-08-04 15:01:58 -0700766 private int getConnectivityChangeDelay() {
767 final ContentResolver cr = mContext.getContentResolver();
768
769 /** Check system properties for the default value then use secure settings value, if any. */
770 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey8c870452012-09-26 22:03:49 -0700771 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
772 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
773 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700774 defaultDelay);
775 }
776
The Android Open Source Project28527d22009-03-03 19:31:44 -0800777 private int getPersistedNetworkPreference() {
778 final ContentResolver cr = mContext.getContentResolver();
779
Jeff Brownc67cf562012-09-25 15:03:20 -0700780 final int networkPrefSetting = Settings.Global
781 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800782
Jianzheng Zhou028d2032012-11-16 13:45:20 +0800783 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800784 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700785
The Android Open Source Project28527d22009-03-03 19:31:44 -0800786 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700787 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800788 * In this method, we only tear down a non-preferred network. Establishing
789 * a connection to the preferred network is taken care of when we handle
790 * the disconnect event from the non-preferred network
791 * (see {@link #handleDisconnect(NetworkInfo)}).
792 */
793 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700794 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800795 return;
796
Robert Greenwalt2034b912009-08-12 16:08:25 -0700797 if (!mNetTrackers[mNetworkPreference].isAvailable())
798 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800799
Robert Greenwalt2034b912009-08-12 16:08:25 -0700800 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700801 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700802 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700803 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800804 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700805 " in enforcePreference");
806 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700807 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800808 }
809 }
810 }
811
812 private boolean teardown(NetworkStateTracker netTracker) {
813 if (netTracker.teardown()) {
814 netTracker.setTeardownRequested(true);
815 return true;
816 } else {
817 return false;
818 }
819 }
820
821 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700822 * Check if UID should be blocked from using the network represented by the
823 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700824 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700825 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
826 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700827
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700828 final boolean networkCostly;
829 final int uidRules;
830 synchronized (mRulesLock) {
831 networkCostly = mMeteredIfaces.contains(iface);
832 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700833 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700834
835 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
836 return true;
837 }
838
839 // no restrictive rules; network is visible
840 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700841 }
842
843 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700844 * Return a filtered {@link NetworkInfo}, potentially marked
845 * {@link DetailedState#BLOCKED} based on
846 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700847 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700848 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
849 NetworkInfo info = tracker.getNetworkInfo();
850 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700851 // network is blocked; clone and override state
852 info = new NetworkInfo(info);
853 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700854 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700855 if (mLockdownTracker != null) {
856 info = mLockdownTracker.augmentNetworkInfo(info);
857 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700858 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700859 }
860
861 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800862 * Return NetworkInfo for the active (i.e., connected) network interface.
863 * It is assumed that at most one network is active at a time. If more
864 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700865 * @return the info for the active network, or {@code null} if none is
866 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800867 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700868 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800869 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700870 enforceAccessPermission();
871 final int uid = Binder.getCallingUid();
872 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800873 }
874
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700875 public NetworkInfo getActiveNetworkInfoUnfiltered() {
876 enforceAccessPermission();
877 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
878 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
879 if (tracker != null) {
880 return tracker.getNetworkInfo();
881 }
882 }
883 return null;
884 }
885
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700886 @Override
887 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
888 enforceConnectivityInternalPermission();
889 return getNetworkInfo(mActiveDefaultNetwork, uid);
890 }
891
892 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800893 public NetworkInfo getNetworkInfo(int networkType) {
894 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700895 final int uid = Binder.getCallingUid();
896 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800897 }
898
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700899 private NetworkInfo getNetworkInfo(int networkType, int uid) {
900 NetworkInfo info = null;
901 if (isNetworkTypeValid(networkType)) {
902 final NetworkStateTracker tracker = mNetTrackers[networkType];
903 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700904 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700905 }
906 }
907 return info;
908 }
909
910 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800911 public NetworkInfo[] getAllNetworkInfo() {
912 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700913 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700914 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700915 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700916 for (NetworkStateTracker tracker : mNetTrackers) {
917 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700918 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700919 }
920 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800921 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700922 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800923 }
924
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700925 @Override
926 public boolean isNetworkSupported(int networkType) {
927 enforceAccessPermission();
928 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
929 }
930
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700931 /**
932 * Return LinkProperties for the active (i.e., connected) default
933 * network interface. It is assumed that at most one default network
934 * is active at a time. If more than one is active, it is indeterminate
935 * which will be returned.
936 * @return the ip properties for the active network, or {@code null} if
937 * none is active
938 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700939 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700940 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700941 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700942 }
943
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700944 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700945 public LinkProperties getLinkProperties(int networkType) {
946 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700947 if (isNetworkTypeValid(networkType)) {
948 final NetworkStateTracker tracker = mNetTrackers[networkType];
949 if (tracker != null) {
950 return tracker.getLinkProperties();
951 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700952 }
953 return null;
954 }
955
Jeff Sharkey21062e72011-05-28 20:56:34 -0700956 @Override
957 public NetworkState[] getAllNetworkState() {
958 enforceAccessPermission();
959 final int uid = Binder.getCallingUid();
960 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700961 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700962 for (NetworkStateTracker tracker : mNetTrackers) {
963 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700964 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700965 result.add(new NetworkState(
966 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
967 }
968 }
969 }
970 return result.toArray(new NetworkState[result.size()]);
971 }
972
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700973 private NetworkState getNetworkStateUnchecked(int networkType) {
974 if (isNetworkTypeValid(networkType)) {
975 final NetworkStateTracker tracker = mNetTrackers[networkType];
976 if (tracker != null) {
977 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
978 tracker.getLinkCapabilities());
979 }
980 }
981 return null;
982 }
983
984 @Override
985 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
986 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700987
988 final long token = Binder.clearCallingIdentity();
989 try {
990 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
991 if (state != null) {
992 try {
993 return mPolicyManager.getNetworkQuotaInfo(state);
994 } catch (RemoteException e) {
995 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700996 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700997 return null;
998 } finally {
999 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001000 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001001 }
1002
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001003 @Override
1004 public boolean isActiveNetworkMetered() {
1005 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001006 final long token = Binder.clearCallingIdentity();
1007 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001008 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001009 } finally {
1010 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001011 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001012 }
1013
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001014 private boolean isNetworkMeteredUnchecked(int networkType) {
1015 final NetworkState state = getNetworkStateUnchecked(networkType);
1016 if (state != null) {
1017 try {
1018 return mPolicyManager.isNetworkMetered(state);
1019 } catch (RemoteException e) {
1020 }
1021 }
1022 return false;
1023 }
1024
The Android Open Source Project28527d22009-03-03 19:31:44 -08001025 public boolean setRadios(boolean turnOn) {
1026 boolean result = true;
1027 enforceChangePermission();
1028 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001029 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001030 }
1031 return result;
1032 }
1033
1034 public boolean setRadio(int netType, boolean turnOn) {
1035 enforceChangePermission();
1036 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1037 return false;
1038 }
1039 NetworkStateTracker tracker = mNetTrackers[netType];
1040 return tracker != null && tracker.setRadio(turnOn);
1041 }
1042
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001043 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1044 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001045 public void interfaceClassDataActivityChanged(String label, boolean active) {
1046 int deviceType = Integer.parseInt(label);
1047 sendDataActivityBroadcast(deviceType, active);
1048 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001049 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001050
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001051 /**
1052 * Used to notice when the calling process dies so we can self-expire
1053 *
1054 * Also used to know if the process has cleaned up after itself when
1055 * our auto-expire timer goes off. The timer has a link to an object.
1056 *
1057 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001058 private class FeatureUser implements IBinder.DeathRecipient {
1059 int mNetworkType;
1060 String mFeature;
1061 IBinder mBinder;
1062 int mPid;
1063 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001064 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001065
1066 FeatureUser(int type, String feature, IBinder binder) {
1067 super();
1068 mNetworkType = type;
1069 mFeature = feature;
1070 mBinder = binder;
1071 mPid = getCallingPid();
1072 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001073 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001074
Robert Greenwalt2034b912009-08-12 16:08:25 -07001075 try {
1076 mBinder.linkToDeath(this, 0);
1077 } catch (RemoteException e) {
1078 binderDied();
1079 }
1080 }
1081
1082 void unlinkDeathRecipient() {
1083 mBinder.unlinkToDeath(this, 0);
1084 }
1085
1086 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001087 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001088 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1089 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001090 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001091 }
1092
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001093 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001094 if (VDBG) {
1095 log("ConnectivityService FeatureUser expire(" +
1096 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1097 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1098 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001099 stopUsingNetworkFeature(this, false);
1100 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001101
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001102 public boolean isSameUser(FeatureUser u) {
1103 if (u == null) return false;
1104
1105 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1106 }
1107
1108 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1109 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1110 TextUtils.equals(mFeature, feature)) {
1111 return true;
1112 }
1113 return false;
1114 }
1115
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001116 public String toString() {
1117 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1118 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1119 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001120 }
1121
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001122 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001123 public int startUsingNetworkFeature(int networkType, String feature,
1124 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001125 long startTime = 0;
1126 if (DBG) {
1127 startTime = SystemClock.elapsedRealtime();
1128 }
Wink Savillea7d56572011-09-21 11:05:43 -07001129 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001130 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1131 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001132 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001133 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001134 try {
1135 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1136 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001137 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001138 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001139
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001140 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001141
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001142 // TODO - move this into individual networktrackers
1143 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001144
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001145 if (mLockdownEnabled) {
1146 // Since carrier APNs usually aren't available from VPN
1147 // endpoint, mark them as unavailable.
1148 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1149 }
1150
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001151 if (mProtectedNetworks.contains(usedNetworkType)) {
1152 enforceConnectivityInternalPermission();
1153 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001154
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001155 // if UID is restricted, don't allow them to bring up metered APNs
1156 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1157 final int uidRules;
1158 synchronized (mRulesLock) {
1159 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1160 }
1161 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001162 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001163 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001164
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001165 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1166 if (network != null) {
1167 Integer currentPid = new Integer(getCallingPid());
1168 if (usedNetworkType != networkType) {
1169 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001170
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001171 if (ni.isAvailable() == false) {
1172 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1173 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001174 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001175 } else {
1176 // else make the attempt anyway - probably giving REQUEST_STARTED below
1177 if (DBG) {
1178 log("special network not available, but try anyway ni=" +
1179 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001180 }
1181 }
1182 }
1183
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001184 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001185
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001186 synchronized(this) {
1187 boolean addToList = true;
1188 if (restoreTimer < 0) {
1189 // In case there is no timer is specified for the feature,
1190 // make sure we don't add duplicate entry with the same request.
1191 for (FeatureUser u : mFeatureUsers) {
1192 if (u.isSameUser(f)) {
1193 // Duplicate user is found. Do not add.
1194 addToList = false;
1195 break;
1196 }
1197 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001198 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001199
1200 if (addToList) mFeatureUsers.add(f);
1201 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1202 // this gets used for per-pid dns when connected
1203 mNetRequestersPids[usedNetworkType].add(currentPid);
1204 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001205 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001206
1207 if (restoreTimer >= 0) {
1208 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1209 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1210 }
1211
1212 if ((ni.isConnectedOrConnecting() == true) &&
1213 !network.isTeardownRequested()) {
1214 if (ni.isConnected() == true) {
1215 final long token = Binder.clearCallingIdentity();
1216 try {
1217 // add the pid-specific dns
1218 handleDnsConfigurationChange(usedNetworkType);
1219 if (VDBG) log("special network already active");
1220 } finally {
1221 Binder.restoreCallingIdentity(token);
1222 }
Wink Saville64e3f782012-07-10 12:37:54 -07001223 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001224 }
1225 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001226 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001227 }
1228
1229 // check if the radio in play can make another contact
1230 // assume if cannot for now
1231
1232 if (DBG) {
1233 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1234 feature);
1235 }
Mikael Hedegrenc6534b52012-12-14 15:52:52 +01001236 if (network.reconnect()) {
1237 return PhoneConstants.APN_REQUEST_STARTED;
1238 } else {
1239 return PhoneConstants.APN_REQUEST_FAILED;
1240 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001241 } else {
1242 // need to remember this unsupported request so we respond appropriately on stop
1243 synchronized(this) {
1244 mFeatureUsers.add(f);
1245 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1246 // this gets used for per-pid dns when connected
1247 mNetRequestersPids[usedNetworkType].add(currentPid);
1248 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001249 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001250 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001251 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001252 }
Wink Saville64e3f782012-07-10 12:37:54 -07001253 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001254 } finally {
1255 if (DBG) {
1256 final long execTime = SystemClock.elapsedRealtime() - startTime;
1257 if (execTime > 250) {
1258 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1259 } else {
1260 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1261 }
1262 }
1263 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001264 }
1265
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001266 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001267 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001268 enforceChangePermission();
1269
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001270 int pid = getCallingPid();
1271 int uid = getCallingUid();
1272
1273 FeatureUser u = null;
1274 boolean found = false;
1275
1276 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001277 for (FeatureUser x : mFeatureUsers) {
1278 if (x.isSameUser(pid, uid, networkType, feature)) {
1279 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001280 found = true;
1281 break;
1282 }
1283 }
1284 }
1285 if (found && u != null) {
1286 // stop regardless of how many other time this proc had called start
1287 return stopUsingNetworkFeature(u, true);
1288 } else {
1289 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001290 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001291 return 1;
1292 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001293 }
1294
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001295 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1296 int networkType = u.mNetworkType;
1297 String feature = u.mFeature;
1298 int pid = u.mPid;
1299 int uid = u.mUid;
1300
1301 NetworkStateTracker tracker = null;
1302 boolean callTeardown = false; // used to carry our decision outside of sync block
1303
Wink Savillea7d56572011-09-21 11:05:43 -07001304 if (VDBG) {
1305 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001306 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001307
The Android Open Source Project28527d22009-03-03 19:31:44 -08001308 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001309 if (DBG) {
1310 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1311 ", net is invalid");
1312 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001313 return -1;
1314 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001315
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001316 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1317 // sync block
1318 synchronized(this) {
1319 // check if this process still has an outstanding start request
1320 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001321 if (VDBG) {
1322 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1323 ", ignoring");
1324 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001325 return 1;
1326 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001327 u.unlinkDeathRecipient();
1328 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1329 // If we care about duplicate requests, check for that here.
1330 //
1331 // This is done to support the extension of a request - the app
1332 // can request we start the network feature again and renew the
1333 // auto-shutoff delay. Normal "stop" calls from the app though
1334 // do not pay attention to duplicate requests - in effect the
1335 // API does not refcount and a single stop will counter multiple starts.
1336 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001337 for (FeatureUser x : mFeatureUsers) {
1338 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001339 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001340 return 1;
1341 }
1342 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001343 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001344
repo syncf5de5572011-07-29 23:55:49 -07001345 // TODO - move to individual network trackers
1346 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1347
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001348 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001349 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001350 if (DBG) {
1351 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1352 " no known tracker for used net type " + usedNetworkType);
1353 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001354 return -1;
1355 }
1356 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001357 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001358 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalte767d812013-02-12 17:18:25 -08001359
1360 final long token = Binder.clearCallingIdentity();
1361 try {
1362 reassessPidDns(pid, true);
1363 } finally {
1364 Binder.restoreCallingIdentity(token);
1365 }
Mattias Falkd697aa22011-08-23 14:15:13 +02001366 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001367 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001368 if (VDBG) {
1369 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1370 " others still using it");
1371 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001372 return 1;
1373 }
1374 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001375 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001376 if (DBG) {
1377 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1378 " not a known feature - dropping");
1379 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001380 }
1381 }
Wink Savillea7d56572011-09-21 11:05:43 -07001382
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001383 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001384 if (DBG) {
1385 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1386 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001387 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001388 return 1;
1389 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001390 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001391 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001392 }
1393
1394 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001395 * @deprecated use requestRouteToHostAddress instead
1396 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001397 * Ensure that a network route exists to deliver traffic to the specified
1398 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001399 * @param networkType the type of the network over which traffic to the
1400 * specified host is to be routed
1401 * @param hostAddress the IP address of the host to which the route is
1402 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001403 * @return {@code true} on success, {@code false} on failure
1404 */
1405 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001406 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1407
1408 if (inetAddress == null) {
1409 return false;
1410 }
1411
1412 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1413 }
1414
1415 /**
1416 * Ensure that a network route exists to deliver traffic to the specified
1417 * host via the specified network interface.
1418 * @param networkType the type of the network over which traffic to the
1419 * specified host is to be routed
1420 * @param hostAddress the IP address of the host to which the route is
1421 * desired
1422 * @return {@code true} on success, {@code false} on failure
1423 */
1424 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001425 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001426 if (mProtectedNetworks.contains(networkType)) {
1427 enforceConnectivityInternalPermission();
1428 }
1429
The Android Open Source Project28527d22009-03-03 19:31:44 -08001430 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001431 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001432 return false;
1433 }
1434 NetworkStateTracker tracker = mNetTrackers[networkType];
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001435 DetailedState netState = tracker.getNetworkInfo().getDetailedState();
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001436
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07001437 if (tracker == null || (netState != DetailedState.CONNECTED &&
1438 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001439 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001440 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07001441 log("requestRouteToHostAddress on down network "
1442 + "(" + networkType + ") - dropped"
1443 + " tracker=" + tracker
1444 + " netState=" + netState
1445 + " isTeardownRequested="
1446 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001447 }
1448 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001449 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001450 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001451 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001452 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001453 LinkProperties lp = tracker.getLinkProperties();
Wink Saville32506bc2013-06-29 21:10:57 -07001454 boolean ok = addRouteToAddress(lp, addr);
1455 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1456 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001457 } catch (UnknownHostException e) {
1458 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1459 } finally {
1460 Binder.restoreCallingIdentity(token);
1461 }
Wink Saville32506bc2013-06-29 21:10:57 -07001462 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001463 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001464 }
1465
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001466 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001467 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001468 }
1469
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001470 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001471 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001472 }
1473
Robert Greenwalt98107422011-07-22 11:55:33 -07001474 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001475 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001476 }
1477
1478 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001479 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001480 }
1481
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001482 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1483 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001484 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001485 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001486 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001487 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001488 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001489 if (bestRoute.getGateway().equals(addr)) {
1490 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001491 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001492 } else {
1493 // if we will connect to this through another route, add a direct route
1494 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001495 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001496 }
1497 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001498 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001499 }
1500
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001501 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1502 boolean toDefaultTable) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001503 if ((lp == null) || (r == null)) {
1504 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001505 return false;
1506 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001507
1508 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001509 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001510 return false;
1511 }
1512
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001513 String ifaceName = r.getInterface();
1514 if(ifaceName == null) {
1515 loge("Error modifying route - no interface name");
1516 return false;
1517 }
Robert Greenwalt59070cf2013-04-11 13:48:16 -07001518 if (r.hasGateway()) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09001519 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001520 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001521 if (bestRoute.getGateway().equals(r.getGateway())) {
1522 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001523 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001524 } else {
1525 // if we will connect to our gateway through another route, add a direct
1526 // route to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08001527 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1528 bestRoute.getGateway(),
1529 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001530 }
Lorenzo Colitti53de3362013-03-12 07:39:59 +09001531 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001532 }
1533 }
1534 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001535 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001536 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001537 if (toDefaultTable) {
1538 mAddedRoutes.add(r); // only track default table - only one apps can effect
1539 mNetd.addRoute(ifaceName, r);
1540 } else {
1541 mNetd.addSecondaryRoute(ifaceName, r);
1542 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001543 } catch (Exception e) {
1544 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001545 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001546 return false;
1547 }
1548 } else {
1549 // if we remove this one and there are no more like it, then refcount==0 and
1550 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001551 if (toDefaultTable) {
1552 mAddedRoutes.remove(r);
1553 if (mAddedRoutes.contains(r) == false) {
1554 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1555 try {
1556 mNetd.removeRoute(ifaceName, r);
1557 } catch (Exception e) {
1558 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001559 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001560 return false;
1561 }
1562 } else {
1563 if (VDBG) log("not removing " + r + " as it's still in use");
1564 }
1565 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001566 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001567 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001568 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001569 } catch (Exception e) {
1570 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001571 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001572 return false;
1573 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001574 }
1575 }
1576 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001577 }
1578
1579 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001580 * @see ConnectivityManager#getMobileDataEnabled()
1581 */
1582 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001583 // TODO: This detail should probably be in DataConnectionTracker's
1584 // which is where we store the value and maybe make this
1585 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001586 enforceAccessPermission();
Jeff Sharkey8b361572012-09-26 15:54:06 -07001587 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1588 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001589 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001590 return retVal;
1591 }
1592
Robert Greenwalt34848c02011-03-25 13:09:25 -07001593 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001594 enforceConnectivityInternalPermission();
1595
Robert Greenwalt34848c02011-03-25 13:09:25 -07001596 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1597 (met ? ENABLED : DISABLED), networkType));
1598 }
1599
1600 private void handleSetDependencyMet(int networkType, boolean met) {
1601 if (mNetTrackers[networkType] != null) {
1602 if (DBG) {
1603 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1604 }
1605 mNetTrackers[networkType].setDependencyMet(met);
1606 }
1607 }
1608
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001609 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1610 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001611 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001612 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001613 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001614 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001615 }
1616
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001617 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001618 // skip update when we've already applied rules
1619 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1620 if (oldRules == uidRules) return;
1621
1622 mUidRules.put(uid, uidRules);
1623 }
1624
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001625 // TODO: notify UID when it has requested targeted updates
1626 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001627
1628 @Override
1629 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001630 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001631 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001632 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001633 }
1634
1635 synchronized (mRulesLock) {
1636 mMeteredIfaces.clear();
1637 for (String iface : meteredIfaces) {
1638 mMeteredIfaces.add(iface);
1639 }
1640 }
1641 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001642
1643 @Override
1644 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1645 // caller is NPMS, since we only register with them
1646 if (LOGD_RULES) {
1647 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1648 }
1649
1650 // kick off connectivity change broadcast for active network, since
1651 // global background policy change is radical.
1652 final int networkType = mActiveDefaultNetwork;
1653 if (isNetworkTypeValid(networkType)) {
1654 final NetworkStateTracker tracker = mNetTrackers[networkType];
1655 if (tracker != null) {
1656 final NetworkInfo info = tracker.getNetworkInfo();
1657 if (info != null && info.isConnected()) {
1658 sendConnectedBroadcast(info);
1659 }
1660 }
1661 }
1662 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001663 };
1664
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001665 /**
1666 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1667 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001668 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001669 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001670 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001671
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001672 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001673 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001674 }
1675
1676 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001677 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001678 if (VDBG) {
1679 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001680 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001681 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1682 }
tk.mun5eee1042012-01-06 10:43:52 +09001683 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1684 if (VDBG) {
1685 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1686 }
1687 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1688 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001689 }
1690
1691 @Override
1692 public void setPolicyDataEnable(int networkType, boolean enabled) {
1693 // only someone like NPMS should only be calling us
1694 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1695
1696 mHandler.sendMessage(mHandler.obtainMessage(
1697 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1698 }
1699
1700 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1701 if (isNetworkTypeValid(networkType)) {
1702 final NetworkStateTracker tracker = mNetTrackers[networkType];
1703 if (tracker != null) {
1704 tracker.setPolicyDataEnable(enabled);
1705 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001706 }
1707 }
1708
The Android Open Source Project28527d22009-03-03 19:31:44 -08001709 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001710 mContext.enforceCallingOrSelfPermission(
1711 android.Manifest.permission.ACCESS_NETWORK_STATE,
1712 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001713 }
1714
1715 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001716 mContext.enforceCallingOrSelfPermission(
1717 android.Manifest.permission.CHANGE_NETWORK_STATE,
1718 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001719 }
1720
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001721 // TODO Make this a special check when it goes public
1722 private void enforceTetherChangePermission() {
1723 mContext.enforceCallingOrSelfPermission(
1724 android.Manifest.permission.CHANGE_NETWORK_STATE,
1725 "ConnectivityService");
1726 }
1727
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001728 private void enforceTetherAccessPermission() {
1729 mContext.enforceCallingOrSelfPermission(
1730 android.Manifest.permission.ACCESS_NETWORK_STATE,
1731 "ConnectivityService");
1732 }
1733
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001734 private void enforceConnectivityInternalPermission() {
1735 mContext.enforceCallingOrSelfPermission(
1736 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1737 "ConnectivityService");
1738 }
1739
The Android Open Source Project28527d22009-03-03 19:31:44 -08001740 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001741 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1742 * network, we ignore it. If it is for the active network, we send out a
1743 * broadcast. But first, we check whether it might be possible to connect
1744 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001745 * @param info the {@code NetworkInfo} for the network
1746 */
1747 private void handleDisconnect(NetworkInfo info) {
1748
Robert Greenwalt2034b912009-08-12 16:08:25 -07001749 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001750
Robert Greenwalt2034b912009-08-12 16:08:25 -07001751 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Baie2462442012-06-28 15:26:19 -07001752
1753 // Remove idletimer previously setup in {@code handleConnect}
1754 removeDataActivityTracking(prevNetType);
1755
The Android Open Source Project28527d22009-03-03 19:31:44 -08001756 /*
1757 * If the disconnected network is not the active one, then don't report
1758 * this as a loss of connectivity. What probably happened is that we're
1759 * getting the disconnect for a network that we explicitly disabled
1760 * in accordance with network preference policies.
1761 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001762 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkd697aa22011-08-23 14:15:13 +02001763 List<Integer> pids = mNetRequestersPids[prevNetType];
1764 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001765 // will remove them because the net's no longer connected
1766 // need to do this now as only now do we know the pids and
1767 // can properly null things that are no longer referenced.
1768 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001769 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001770 }
1771
The Android Open Source Project28527d22009-03-03 19:31:44 -08001772 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001773 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001774 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001775 if (info.isFailover()) {
1776 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1777 info.setFailover(false);
1778 }
1779 if (info.getReason() != null) {
1780 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1781 }
1782 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001783 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1784 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001785 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001786
Robert Greenwalt34848c02011-03-25 13:09:25 -07001787 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001788 tryFailover(prevNetType);
1789 if (mActiveDefaultNetwork != -1) {
1790 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001791 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1792 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001793 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001794 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1795 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001796 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001797 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001798
1799 // Reset interface if no other connections are using the same interface
1800 boolean doReset = true;
1801 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1802 if (linkProperties != null) {
1803 String oldIface = linkProperties.getInterfaceName();
1804 if (TextUtils.isEmpty(oldIface) == false) {
1805 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1806 if (networkStateTracker == null) continue;
1807 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1808 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1809 LinkProperties l = networkStateTracker.getLinkProperties();
1810 if (l == null) continue;
1811 if (oldIface.equals(l.getInterfaceName())) {
1812 doReset = false;
1813 break;
1814 }
1815 }
1816 }
1817 }
1818 }
1819
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001820 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001821 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001822
Jeff Sharkey971cd162011-08-29 16:02:57 -07001823 final Intent immediateIntent = new Intent(intent);
1824 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1825 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001826 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001827 /*
1828 * If the failover network is already connected, then immediately send
1829 * out a followup broadcast indicating successful failover
1830 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001831 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001832 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1833 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001834 }
1835 }
1836
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001837 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001838 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001839 * If this is a default network, check if other defaults are available.
1840 * Try to reconnect on all available and let them hash it out when
1841 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001842 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001843 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001844 if (mActiveDefaultNetwork == prevNetType) {
1845 mActiveDefaultNetwork = -1;
1846 }
1847
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001848 // don't signal a reconnect for anything lower or equal priority than our
1849 // current connected default
1850 // TODO - don't filter by priority now - nice optimization but risky
1851// int currentPriority = -1;
1852// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001853// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001854// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001855 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001856 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001857 if (mNetConfigs[checkType] == null) continue;
1858 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001859 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001860
1861// Enabling the isAvailable() optimization caused mobile to not get
1862// selected if it was in the middle of error handling. Specifically
1863// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1864// would not be available and we wouldn't get connected to anything.
1865// So removing the isAvailable() optimization below for now. TODO: This
1866// optimization should work and we need to investigate why it doesn't work.
1867// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1868// complete before it is really complete.
1869// if (!mNetTrackers[checkType].isAvailable()) continue;
1870
Robert Greenwalt34848c02011-03-25 13:09:25 -07001871// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001872
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001873 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1874 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1875 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1876 checkInfo.setFailover(true);
1877 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001878 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001879 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001880 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001881 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001882 }
1883
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001884 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08001885 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07001886 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1887 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001888 }
1889
Wink Saville4f0de1e2011-08-04 15:01:58 -07001890 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001891 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1892 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001893 }
1894
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001895 private void sendInetConditionBroadcast(NetworkInfo info) {
1896 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1897 }
1898
Wink Saville4f0de1e2011-08-04 15:01:58 -07001899 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07001900 if (mLockdownTracker != null) {
1901 info = mLockdownTracker.augmentNetworkInfo(info);
1902 }
1903
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001904 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001905 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001906 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001907 if (info.isFailover()) {
1908 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1909 info.setFailover(false);
1910 }
1911 if (info.getReason() != null) {
1912 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1913 }
1914 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001915 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1916 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001917 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001918 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001919 return intent;
1920 }
1921
1922 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1923 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1924 }
1925
1926 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1927 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001928 }
1929
Haoyu Baib5da5752012-06-20 14:29:57 -07001930 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1931 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1932 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1933 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborne588ca12012-09-04 18:48:37 -07001934 final long ident = Binder.clearCallingIdentity();
1935 try {
1936 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1937 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1938 } finally {
1939 Binder.restoreCallingIdentity(ident);
1940 }
Haoyu Baib5da5752012-06-20 14:29:57 -07001941 }
1942
The Android Open Source Project28527d22009-03-03 19:31:44 -08001943 /**
1944 * Called when an attempt to fail over to another network has failed.
1945 * @param info the {@link NetworkInfo} for the failed network
1946 */
1947 private void handleConnectionFailure(NetworkInfo info) {
1948 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001949
Robert Greenwalt2034b912009-08-12 16:08:25 -07001950 String reason = info.getReason();
1951 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001952
Robert Greenwalte981bc52010-10-08 16:35:52 -07001953 String reasonText;
1954 if (reason == null) {
1955 reasonText = ".";
1956 } else {
1957 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001958 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001959 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001960
1961 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07001962 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001963 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001964 if (getActiveNetworkInfo() == null) {
1965 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1966 }
1967 if (reason != null) {
1968 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1969 }
1970 if (extraInfo != null) {
1971 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1972 }
1973 if (info.isFailover()) {
1974 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1975 info.setFailover(false);
1976 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001977
Robert Greenwalt34848c02011-03-25 13:09:25 -07001978 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001979 tryFailover(info.getType());
1980 if (mActiveDefaultNetwork != -1) {
1981 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001982 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1983 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001984 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001985 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1986 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001987 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001988
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001989 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07001990
1991 final Intent immediateIntent = new Intent(intent);
1992 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1993 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001994 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001995 /*
1996 * If the failover network is already connected, then immediately send
1997 * out a followup broadcast indicating successful failover
1998 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001999 if (mActiveDefaultNetwork != -1) {
2000 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002001 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002002 }
2003
2004 private void sendStickyBroadcast(Intent intent) {
2005 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002006 if (!mSystemReady) {
2007 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002008 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002009 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002010 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002011 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002012 }
2013
Dianne Hackborne588ca12012-09-04 18:48:37 -07002014 final long ident = Binder.clearCallingIdentity();
2015 try {
2016 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2017 } finally {
2018 Binder.restoreCallingIdentity(ident);
2019 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002020 }
2021 }
2022
Wink Saville4f0de1e2011-08-04 15:01:58 -07002023 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2024 if (delayMs <= 0) {
2025 sendStickyBroadcast(intent);
2026 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002027 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002028 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2029 + intent.getAction());
2030 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002031 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2032 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2033 }
2034 }
2035
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002036 void systemReady() {
2037 synchronized(this) {
2038 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002039 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002040 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002041 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002042 }
2043 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002044 // load the global proxy at startup
2045 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002046
2047 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2048 // for user to unlock device.
2049 if (!updateLockdownVpn()) {
2050 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2051 mContext.registerReceiver(mUserPresentReceiver, filter);
2052 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002053 }
2054
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002055 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2056 @Override
2057 public void onReceive(Context context, Intent intent) {
2058 // Try creating lockdown tracker, since user present usually means
2059 // unlocked keystore.
2060 if (updateLockdownVpn()) {
2061 mContext.unregisterReceiver(this);
2062 }
2063 }
2064 };
2065
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002066 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2067 if ((type != mNetworkPreference &&
2068 mNetConfigs[mActiveDefaultNetwork].priority >
2069 mNetConfigs[type].priority) ||
2070 mNetworkPreference == mActiveDefaultNetwork) return false;
2071 return true;
2072 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002073
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002074 private void handleConnect(NetworkInfo info) {
2075 final int newNetType = info.getType();
2076
2077 setupDataActivityTracking(newNetType);
Haoyu Baie2462442012-06-28 15:26:19 -07002078
The Android Open Source Project28527d22009-03-03 19:31:44 -08002079 // snapshot isFailover, because sendConnectedBroadcast() resets it
2080 boolean isFailover = info.isFailover();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002081 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002082 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002083
Robert Greenwalt2034b912009-08-12 16:08:25 -07002084 // if this is a default net and other default is running
2085 // kill the one not preferred
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002086 if (mNetConfigs[newNetType].isDefault()) {
2087 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2088 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002089 // tear down the other
2090 NetworkStateTracker otherNet =
2091 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002092 if (DBG) {
2093 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002094 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002095 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002096 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002097 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002098 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002099 return;
2100 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002101 } else {
2102 // don't accept this one
2103 if (VDBG) {
2104 log("Not broadcasting CONNECT_ACTION " +
2105 "to torn down network " + info.getTypeName());
2106 }
2107 teardown(thisNet);
2108 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002109 }
2110 }
2111 synchronized (ConnectivityService.this) {
2112 // have a new default network, release the transition wakelock in a second
2113 // if it's held. The second pause is to allow apps to reconnect over the
2114 // new network
2115 if (mNetTransitionWakeLock.isHeld()) {
2116 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002117 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002118 mNetTransitionWakeLockSerialNumber, 0),
2119 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002120 }
2121 }
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002122 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002123 // this will cause us to come up initially as unconnected and switching
2124 // to connected after our normal pause unless somebody reports us as reall
2125 // disconnected
2126 mDefaultInetConditionPublished = 0;
2127 mDefaultConnectionSequence++;
2128 mInetConditionChangeInFlight = false;
2129 // Don't do this - if we never sign in stay, grey
2130 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002131 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002132 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002133 updateNetworkSettings(thisNet);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002134 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002135 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002136
2137 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002138 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002139 try {
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002140 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002141 } catch (RemoteException e) {
2142 // ignored; service lives in system_server
2143 }
2144 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002145 }
2146
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002147 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2148 if (DBG) log("Captive portal check " + info);
2149 int type = info.getType();
2150 final NetworkStateTracker thisNet = mNetTrackers[type];
2151 if (mNetConfigs[type].isDefault()) {
2152 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2153 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2154 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002155 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002156 return;
2157 } else {
2158 if (DBG) log("Tear down low priority net " + info.getTypeName());
2159 teardown(thisNet);
2160 return;
2161 }
2162 }
2163 }
2164
2165 thisNet.captivePortalCheckComplete();
2166 }
2167
2168 /** @hide */
2169 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002170 enforceConnectivityInternalPermission();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002171 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002172 }
2173
The Android Open Source Project28527d22009-03-03 19:31:44 -08002174 /**
Haoyu Baie2462442012-06-28 15:26:19 -07002175 * Setup data activity tracking for the given network interface.
2176 *
2177 * Every {@code setupDataActivityTracking} should be paired with a
2178 * {@link removeDataActivityTracking} for cleanup.
2179 */
2180 private void setupDataActivityTracking(int type) {
2181 final NetworkStateTracker thisNet = mNetTrackers[type];
2182 final String iface = thisNet.getLinkProperties().getInterfaceName();
2183
2184 final int timeout;
2185
2186 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002187 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2188 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Baie2462442012-06-28 15:26:19 -07002189 0);
2190 // Canonicalize mobile network type
2191 type = ConnectivityManager.TYPE_MOBILE;
2192 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brownc67cf562012-09-25 15:03:20 -07002193 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2194 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Baie2462442012-06-28 15:26:19 -07002195 0);
2196 } else {
2197 // do not track any other networks
2198 timeout = 0;
2199 }
2200
2201 if (timeout > 0 && iface != null) {
2202 try {
2203 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2204 } catch (RemoteException e) {
2205 }
2206 }
2207 }
2208
2209 /**
2210 * Remove data activity tracking when network disconnects.
2211 */
2212 private void removeDataActivityTracking(int type) {
2213 final NetworkStateTracker net = mNetTrackers[type];
2214 final String iface = net.getLinkProperties().getInterfaceName();
2215
2216 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2217 ConnectivityManager.TYPE_WIFI == type)) {
2218 try {
2219 // the call fails silently if no idletimer setup for this interface
2220 mNetd.removeIdleTimer(iface);
2221 } catch (RemoteException e) {
2222 }
2223 }
2224 }
2225
2226 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002227 * After a change in the connectivity state of a network. We're mainly
2228 * concerned with making sure that the list of DNS servers is set up
2229 * according to which networks are connected, and ensuring that the
2230 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002231 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002232 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002233 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2234
The Android Open Source Project28527d22009-03-03 19:31:44 -08002235 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002236 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002237 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002238 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002239 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002240
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002241 LinkProperties curLp = mCurrentLinkProperties[netType];
2242 LinkProperties newLp = null;
2243
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002244 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002245 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002246 if (VDBG) {
2247 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2248 " doReset=" + doReset + " resetMask=" + resetMask +
2249 "\n curLp=" + curLp +
2250 "\n newLp=" + newLp);
2251 }
2252
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002253 if (curLp != null) {
2254 if (curLp.isIdenticalInterfaceName(newLp)) {
2255 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2256 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2257 for (LinkAddress linkAddr : car.removed) {
2258 if (linkAddr.getAddress() instanceof Inet4Address) {
2259 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2260 }
2261 if (linkAddr.getAddress() instanceof Inet6Address) {
2262 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2263 }
Wink Saville051a6642011-07-13 13:44:13 -07002264 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002265 if (DBG) {
2266 log("handleConnectivityChange: addresses changed" +
2267 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2268 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002269 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002270 } else {
2271 if (DBG) {
2272 log("handleConnectivityChange: address are the same reset per doReset" +
2273 " linkProperty[" + netType + "]:" +
2274 " resetMask=" + resetMask);
2275 }
Wink Saville051a6642011-07-13 13:44:13 -07002276 }
2277 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002278 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002279 if (DBG) {
2280 log("handleConnectivityChange: interface not not equivalent reset both" +
2281 " linkProperty[" + netType + "]:" +
2282 " resetMask=" + resetMask);
2283 }
Wink Saville051a6642011-07-13 13:44:13 -07002284 }
Wink Saville051a6642011-07-13 13:44:13 -07002285 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002286 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002287 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002288 }
2289 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002290 if (VDBG) {
2291 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2292 " doReset=" + doReset + " resetMask=" + resetMask +
2293 "\n curLp=" + curLp +
2294 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002295 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002296 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002297 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07002298 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002299
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002300 if (resetMask != 0 || resetDns) {
Robert Greenwalt4398f342013-05-23 18:33:06 -07002301 if (curLp != null) {
2302 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colitti63839822013-03-20 19:22:58 +09002303 if (TextUtils.isEmpty(iface) == false) {
2304 if (resetMask != 0) {
2305 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2306 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002307
Lorenzo Colitti63839822013-03-20 19:22:58 +09002308 // Tell VPN the interface is down. It is a temporary
2309 // but effective fix to make VPN aware of the change.
2310 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2311 mVpn.interfaceStatusChanged(iface, false);
2312 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002313 }
Lorenzo Colitti63839822013-03-20 19:22:58 +09002314 if (resetDns) {
2315 flushVmDnsCache();
2316 if (VDBG) log("resetting DNS cache for " + iface);
2317 try {
2318 mNetd.flushInterfaceDnsCache(iface);
2319 } catch (Exception e) {
2320 // never crash - catch them all
2321 if (DBG) loge("Exception resetting dns cache: " + e);
2322 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002323 }
Robert Greenwalt4398f342013-05-23 18:33:06 -07002324 } else {
2325 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002326 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002327 }
2328 }
2329 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002330
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002331 // Update 464xlat state.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002332 NetworkStateTracker tracker = mNetTrackers[netType];
2333 if (mClat.requiresClat(netType, tracker)) {
Lorenzo Colitti4118d082013-03-28 14:13:43 +09002334 // If the connection was previously using clat, but is not using it now, stop the clat
2335 // daemon. Normally, this happens automatically when the connection disconnects, but if
2336 // the disconnect is not reported, or if the connection's LinkProperties changed for
2337 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2338 // still be running. If it's not running, then stopping it is a no-op.
2339 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2340 mClat.stopClat();
2341 }
2342 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti7a9d7972013-03-15 04:22:37 +09002343 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2344 mClat.startClat(tracker);
2345 } else {
2346 mClat.stopClat();
2347 }
2348 }
2349
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002350 // TODO: Temporary notifying upstread change to Tethering.
2351 // @see bug/4455071
2352 /** Notify TetheringService if interface name has been changed. */
2353 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002354 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002355 if (isTetheringSupported()) {
2356 mTethering.handleTetherIfaceChange();
2357 }
2358 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002359 }
2360
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002361 /**
2362 * Add and remove routes using the old properties (null if not previously connected),
2363 * new properties (null if becoming disconnected). May even be double null, which
2364 * is a noop.
2365 * Uses isLinkDefault to determine if default routes should be set or conversely if
2366 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002367 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002368 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002369 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2370 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002371 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002372 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2373 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002374 if (curLp != null) {
2375 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002376 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002377 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002378 } else if (newLp != null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002379 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002380 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002381 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002382
Robert Greenwalt8d777252011-08-15 12:31:55 -07002383 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2384
Robert Greenwalt98107422011-07-22 11:55:33 -07002385 for (RouteInfo r : routeDiff.removed) {
2386 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002387 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2388 }
2389 if (isLinkDefault == false) {
2390 // remove from a secondary route table
2391 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002392 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002393 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002394
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002395 if (!isLinkDefault) {
2396 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002397 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002398 // routes changed - remove all old dns entries and add new
2399 if (curLp != null) {
2400 for (InetAddress oldDns : curLp.getDnses()) {
2401 removeRouteToAddress(curLp, oldDns);
2402 }
2403 }
2404 if (newLp != null) {
2405 for (InetAddress newDns : newLp.getDnses()) {
2406 addRouteToAddress(newLp, newDns);
2407 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002408 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002409 } else {
2410 // no change in routes, check for change in dns themselves
2411 for (InetAddress oldDns : dnsDiff.removed) {
2412 removeRouteToAddress(curLp, oldDns);
2413 }
2414 for (InetAddress newDns : dnsDiff.added) {
2415 addRouteToAddress(newLp, newDns);
2416 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002417 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002418 }
Robert Greenwalt6bd85ba2013-04-05 16:49:32 -07002419
2420 for (RouteInfo r : routeDiff.added) {
2421 if (isLinkDefault || ! r.isDefaultRoute()) {
2422 addRoute(newLp, r, TO_DEFAULT_TABLE);
2423 } else {
2424 // add to a secondary route table
2425 addRoute(newLp, r, TO_SECONDARY_TABLE);
2426
2427 // many radios add a default route even when we don't want one.
2428 // remove the default route unless somebody else has asked for it
2429 String ifaceName = newLp.getInterfaceName();
2430 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2431 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2432 try {
2433 mNetd.removeRoute(ifaceName, r);
2434 } catch (Exception e) {
2435 // never crash - catch them all
2436 if (DBG) loge("Exception trying to remove a route: " + e);
2437 }
2438 }
2439 }
2440 }
2441
Robert Greenwalt8d777252011-08-15 12:31:55 -07002442 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002443 }
2444
2445
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002446 /**
2447 * Reads the network specific TCP buffer sizes from SystemProperties
2448 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2449 * wide use
2450 */
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002451 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002452 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002453 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002454
Jeff Sharkey366e0b72012-08-04 15:24:58 -07002455 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002456 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002457
2458 // Setting to default values so we won't be stuck to previous values
2459 key = "net.tcp.buffersize.default";
2460 bufferSizes = SystemProperties.get(key);
2461 }
2462
2463 // Set values in kernel
2464 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002465 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002466 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002467 + "] which comes from [" + key + "]");
2468 }
2469 setBufferSize(bufferSizes);
2470 }
2471 }
2472
2473 /**
2474 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2475 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2476 *
2477 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2478 * writeMin, writeInitial, writeMax"
2479 */
2480 private void setBufferSize(String bufferSizes) {
2481 try {
2482 String[] values = bufferSizes.split(",");
2483
2484 if (values.length == 6) {
2485 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002486 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2487 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2488 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2489 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2490 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2491 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002492 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002493 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002494 }
2495 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002496 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002497 }
2498 }
2499
Robert Greenwalt2034b912009-08-12 16:08:25 -07002500 /**
2501 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2502 * on the highest priority active net which this process requested.
2503 * If there aren't any, clear it out
2504 */
Mattias Falkd697aa22011-08-23 14:15:13 +02002505 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002506 {
Mattias Falkd697aa22011-08-23 14:15:13 +02002507 if (VDBG) log("reassessPidDns for pid " + pid);
2508 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002509 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002510 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002511 continue;
2512 }
2513 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002514 if (nt.getNetworkInfo().isConnected() &&
2515 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002516 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002517 if (p == null) continue;
Mattias Falkd697aa22011-08-23 14:15:13 +02002518 if (mNetRequestersPids[i].contains(myPid)) {
2519 try {
2520 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2521 } catch (Exception e) {
2522 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002523 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002524 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002525 }
2526 }
2527 }
2528 // nothing found - delete
Mattias Falkd697aa22011-08-23 14:15:13 +02002529 try {
2530 mNetd.clearDnsInterfaceForPid(pid);
2531 } catch (Exception e) {
2532 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002533 }
2534 }
2535
Mattias Falkd697aa22011-08-23 14:15:13 +02002536 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002537 /*
2538 * Tell the VMs to toss their DNS caches
2539 */
2540 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2541 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002542 /*
2543 * Connectivity events can happen before boot has completed ...
2544 */
2545 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002546 final long ident = Binder.clearCallingIdentity();
2547 try {
2548 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2549 } finally {
2550 Binder.restoreCallingIdentity(ident);
2551 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002552 }
2553
Chia-chi Yehcc844502011-07-14 18:01:57 -07002554 // Caller must grab mDnsLock.
Mattias Falkd697aa22011-08-23 14:15:13 +02002555 private void updateDnsLocked(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002556 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002557 int last = 0;
2558 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002559 dnses = new ArrayList();
2560 dnses.add(mDefaultDns);
2561 if (DBG) {
2562 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002563 }
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002564 }
2565
Mattias Falkd697aa22011-08-23 14:15:13 +02002566 try {
2567 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2568 mNetd.setDefaultInterfaceForDns(iface);
Robert Greenwalte41e3b32013-02-11 15:25:10 -08002569 for (InetAddress dns : dnses) {
2570 ++last;
2571 String key = "net.dns" + last;
2572 String value = dns.getHostAddress();
2573 SystemProperties.set(key, value);
2574 }
2575 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2576 String key = "net.dns" + i;
2577 SystemProperties.set(key, "");
2578 }
2579 mNumDnsEntries = last;
Mattias Falkd697aa22011-08-23 14:15:13 +02002580 } catch (Exception e) {
2581 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltd3aec302013-01-19 00:34:07 +00002582 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002583 }
2584
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002585 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002586 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002587 NetworkStateTracker nt = mNetTrackers[netType];
2588 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002589 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002590 if (p == null) return;
2591 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002592 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002593 String network = nt.getNetworkInfo().getTypeName();
2594 synchronized (mDnsLock) {
2595 if (!mDnsOverridden) {
Mattias Falkd697aa22011-08-23 14:15:13 +02002596 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalt94daa182010-09-01 11:34:05 -07002597 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002598 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002599 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002600 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002601 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwaltcd277852012-11-09 10:52:27 -08002602 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002603 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002604 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002605 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002606 // set per-pid dns for attached secondary nets
Mattias Falkd697aa22011-08-23 14:15:13 +02002607 List<Integer> pids = mNetRequestersPids[netType];
2608 for (Integer pid : pids) {
2609 try {
2610 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2611 } catch (Exception e) {
2612 Slog.e(TAG, "exception setting interface for pid: " + e);
2613 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002614 }
2615 }
Mattias Falkd697aa22011-08-23 14:15:13 +02002616 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002617 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002618 }
2619
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002620 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002621 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2622 NETWORK_RESTORE_DELAY_PROP_NAME);
2623 if(restoreDefaultNetworkDelayStr != null &&
2624 restoreDefaultNetworkDelayStr.length() != 0) {
2625 try {
2626 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2627 } catch (NumberFormatException e) {
2628 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002629 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002630 // if the system property isn't set, use the value for the apn type
2631 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2632
2633 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2634 (mNetConfigs[networkType] != null)) {
2635 ret = mNetConfigs[networkType].restoreTime;
2636 }
2637 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002638 }
2639
2640 @Override
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002641 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2642 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002643 if (mContext.checkCallingOrSelfPermission(
2644 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002645 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002646 pw.println("Permission Denial: can't dump ConnectivityService " +
2647 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2648 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002649 return;
2650 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002651
2652 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002653 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002654 for (int i = 0; i < mNetTrackers.length; i++) {
2655 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002656 if (nst != null) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002657 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2658 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002659 if (nst.getNetworkInfo().isConnected()) {
2660 pw.println("Active network: " + nst.getNetworkInfo().
2661 getTypeName());
2662 }
2663 pw.println(nst.getNetworkInfo());
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002664 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002665 pw.println(nst);
2666 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002667 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002668 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002669 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002670
2671 pw.println("Network Requester Pids:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002672 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002673 for (int net : mPriorityList) {
2674 String pidString = net + ": ";
Mattias Falkd697aa22011-08-23 14:15:13 +02002675 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002676 pidString = pidString + pid.toString() + ", ";
2677 }
2678 pw.println(pidString);
2679 }
2680 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002681 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002682
2683 pw.println("FeatureUsers:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002684 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002685 for (Object requester : mFeatureUsers) {
2686 pw.println(requester.toString());
2687 }
2688 pw.println();
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002689 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002690
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002691 synchronized (this) {
2692 pw.println("NetworkTranstionWakeLock is currently " +
2693 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2694 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2695 }
2696 pw.println();
2697
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002698 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002699
2700 if (mInetLog != null) {
2701 pw.println();
2702 pw.println("Inet condition reports:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002703 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002704 for(int i = 0; i < mInetLog.size(); i++) {
2705 pw.println(mInetLog.get(i));
2706 }
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07002707 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002708 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002709 }
2710
Robert Greenwalt2034b912009-08-12 16:08:25 -07002711 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002712 private class NetworkStateTrackerHandler extends Handler {
2713 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002714 super(looper);
2715 }
2716
The Android Open Source Project28527d22009-03-03 19:31:44 -08002717 @Override
2718 public void handleMessage(Message msg) {
2719 NetworkInfo info;
2720 switch (msg.what) {
2721 case NetworkStateTracker.EVENT_STATE_CHANGED:
2722 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002723 int type = info.getType();
2724 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002725
Wink Savillea7d56572011-09-21 11:05:43 -07002726 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2727 (state == NetworkInfo.State.DISCONNECTED)) {
2728 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002729 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002730 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002731 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002732
Jeff Sharkey876ddc92012-11-09 15:57:02 -08002733 EventLogTags.writeConnectivityStateChanged(
2734 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002735
2736 if (info.getDetailedState() ==
2737 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002738 handleConnectionFailure(info);
Irfan Sheriff0ad0d132012-08-16 12:49:23 -07002739 } else if (info.getDetailedState() ==
2740 DetailedState.CAPTIVE_PORTAL_CHECK) {
2741 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002742 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002743 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002744 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002745 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002746 // the logic here is, handle SUSPENDED the same as
2747 // DISCONNECTED. The only difference being we are
2748 // broadcasting an intent with NetworkInfo that's
2749 // suspended. This allows the applications an
2750 // opportunity to handle DISCONNECTED and SUSPENDED
2751 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002752 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002753 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002754 handleConnect(info);
2755 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002756 if (mLockdownTracker != null) {
2757 mLockdownTracker.onNetworkInfoChanged(info);
2758 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002759 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002760 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002761 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002762 // TODO: Temporary allowing network configuration
2763 // change not resetting sockets.
2764 // @see bug/4455071
2765 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002766 break;
Robert Greenwaltadb8bf92012-08-20 11:15:39 -07002767 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2768 info = (NetworkInfo) msg.obj;
2769 type = info.getType();
2770 updateNetworkSettings(mNetTrackers[type]);
2771 break;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002772 }
2773 }
2774 }
2775
2776 private class InternalHandler extends Handler {
2777 public InternalHandler(Looper looper) {
2778 super(looper);
2779 }
2780
2781 @Override
2782 public void handleMessage(Message msg) {
2783 NetworkInfo info;
2784 switch (msg.what) {
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002785 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002786 String causedBy = null;
2787 synchronized (ConnectivityService.this) {
2788 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2789 mNetTransitionWakeLock.isHeld()) {
2790 mNetTransitionWakeLock.release();
2791 causedBy = mNetTransitionWakeLockCausedBy;
2792 }
2793 }
2794 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002795 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002796 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002797 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002798 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002799 FeatureUser u = (FeatureUser)msg.obj;
2800 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002801 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002802 case EVENT_INET_CONDITION_CHANGE:
2803 {
2804 int netType = msg.arg1;
2805 int condition = msg.arg2;
2806 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002807 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002808 }
2809 case EVENT_INET_CONDITION_HOLD_END:
2810 {
2811 int netType = msg.arg1;
2812 int sequence = msg.arg2;
Wink Saville151eaa62013-01-31 00:30:13 +00002813 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002814 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002815 }
2816 case EVENT_SET_NETWORK_PREFERENCE:
2817 {
2818 int preference = msg.arg1;
2819 handleSetNetworkPreference(preference);
2820 break;
2821 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002822 case EVENT_SET_MOBILE_DATA:
2823 {
2824 boolean enabled = (msg.arg1 == ENABLED);
2825 handleSetMobileData(enabled);
2826 break;
2827 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002828 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2829 {
2830 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002831 break;
2832 }
2833 case EVENT_SET_DEPENDENCY_MET:
2834 {
2835 boolean met = (msg.arg1 == ENABLED);
2836 handleSetDependencyMet(msg.arg2, met);
2837 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002838 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002839 case EVENT_RESTORE_DNS:
2840 {
2841 if (mActiveDefaultNetwork != -1) {
2842 handleDnsConfigurationChange(mActiveDefaultNetwork);
2843 }
2844 break;
2845 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002846 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2847 {
2848 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002849 sendStickyBroadcast(intent);
2850 break;
2851 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002852 case EVENT_SET_POLICY_DATA_ENABLE: {
2853 final int networkType = msg.arg1;
2854 final boolean enabled = msg.arg2 == ENABLED;
2855 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002856 break;
2857 }
2858 case EVENT_VPN_STATE_CHANGED: {
2859 if (mLockdownTracker != null) {
2860 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2861 }
2862 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07002863 }
Wink Saville32506bc2013-06-29 21:10:57 -07002864 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2865 int tag = mEnableFailFastMobileDataTag.get();
2866 if (msg.arg1 == tag) {
2867 MobileDataStateTracker mobileDst =
2868 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2869 if (mobileDst != null) {
2870 mobileDst.setEnableFailFastMobileData(msg.arg2);
2871 }
2872 } else {
2873 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2874 + " != tag:" + tag);
2875 }
2876 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002877 }
2878 }
2879 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002880
2881 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002882 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002883 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002884
2885 if (isTetheringSupported()) {
2886 return mTethering.tether(iface);
2887 } else {
2888 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2889 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002890 }
2891
2892 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002893 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002894 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002895
2896 if (isTetheringSupported()) {
2897 return mTethering.untether(iface);
2898 } else {
2899 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2900 }
2901 }
2902
2903 // javadoc from interface
2904 public int getLastTetherError(String iface) {
2905 enforceTetherAccessPermission();
2906
2907 if (isTetheringSupported()) {
2908 return mTethering.getLastTetherError(iface);
2909 } else {
2910 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2911 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002912 }
2913
2914 // TODO - proper iface API for selection by property, inspection, etc
2915 public String[] getTetherableUsbRegexs() {
2916 enforceTetherAccessPermission();
2917 if (isTetheringSupported()) {
2918 return mTethering.getTetherableUsbRegexs();
2919 } else {
2920 return new String[0];
2921 }
2922 }
2923
2924 public String[] getTetherableWifiRegexs() {
2925 enforceTetherAccessPermission();
2926 if (isTetheringSupported()) {
2927 return mTethering.getTetherableWifiRegexs();
2928 } else {
2929 return new String[0];
2930 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002931 }
2932
Danica Chang96567052010-08-11 14:54:43 -07002933 public String[] getTetherableBluetoothRegexs() {
2934 enforceTetherAccessPermission();
2935 if (isTetheringSupported()) {
2936 return mTethering.getTetherableBluetoothRegexs();
2937 } else {
2938 return new String[0];
2939 }
2940 }
2941
Mike Lockwooded4a1742011-07-19 13:04:47 -07002942 public int setUsbTethering(boolean enable) {
Robert Greenwaltfaa4b402013-02-15 10:56:35 -08002943 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07002944 if (isTetheringSupported()) {
2945 return mTethering.setUsbTethering(enable);
2946 } else {
2947 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2948 }
2949 }
2950
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002951 // TODO - move iface listing, queries, etc to new module
2952 // javadoc from interface
2953 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002954 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002955 return mTethering.getTetherableIfaces();
2956 }
2957
2958 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002959 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002960 return mTethering.getTetheredIfaces();
2961 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002962
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002963 @Override
2964 public String[] getTetheredIfacePairs() {
2965 enforceTetherAccessPermission();
2966 return mTethering.getTetheredIfacePairs();
2967 }
2968
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002969 public String[] getTetheringErroredIfaces() {
2970 enforceTetherAccessPermission();
2971 return mTethering.getErroredIfaces();
2972 }
2973
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002974 // if ro.tether.denied = true we default to no tethering
2975 // gservices could set the secure setting to 1 though to enable it on a build where it
2976 // had previously been turned off.
2977 public boolean isTetheringSupported() {
2978 enforceTetherAccessPermission();
2979 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownc67cf562012-09-25 15:03:20 -07002980 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2981 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwaltf1b66e12010-02-25 12:29:30 -08002982 return tetherEnabledInSettings && mTetheringConfigValid;
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002983 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002984
2985 // An API NetworkStateTrackers can call when they lose their network.
2986 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2987 // whichever happens first. The timer is started by the first caller and not
2988 // restarted by subsequent callers.
2989 public void requestNetworkTransitionWakelock(String forWhom) {
2990 enforceConnectivityInternalPermission();
2991 synchronized (this) {
2992 if (mNetTransitionWakeLock.isHeld()) return;
2993 mNetTransitionWakeLockSerialNumber++;
2994 mNetTransitionWakeLock.acquire();
2995 mNetTransitionWakeLockCausedBy = forWhom;
2996 }
2997 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002998 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002999 mNetTransitionWakeLockSerialNumber, 0),
3000 mNetTransitionWakeLockTimeout);
3001 return;
3002 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003003
Robert Greenwalt986c7412010-09-08 15:24:47 -07003004 // 100 percent is full good, 0 is full bad.
3005 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003006 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003007 mContext.enforceCallingOrSelfPermission(
3008 android.Manifest.permission.STATUS_BAR,
3009 "ConnectivityService");
3010
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003011 if (DBG) {
3012 int pid = getCallingPid();
3013 int uid = getCallingUid();
3014 String s = pid + "(" + uid + ") reports inet is " +
3015 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3016 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3017 mInetLog.add(s);
3018 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3019 mInetLog.remove(0);
3020 }
3021 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003022 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003023 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3024 }
3025
3026 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003027 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003028 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003029 return;
3030 }
3031 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003032 if (DBG) log("handleInetConditionChange: net=" + netType +
3033 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003034 return;
3035 }
Wink Savillea7d56572011-09-21 11:05:43 -07003036 if (VDBG) {
3037 log("handleInetConditionChange: net=" +
3038 netType + ", condition=" + condition +
Wink Saville151eaa62013-01-31 00:30:13 +00003039 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003040 }
Wink Saville151eaa62013-01-31 00:30:13 +00003041 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003042 int delay;
3043 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003044 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003045 // setup a new hold to debounce this
Wink Saville151eaa62013-01-31 00:30:13 +00003046 if (mDefaultInetCondition > 50) {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003047 delay = Settings.Global.getInt(mContext.getContentResolver(),
3048 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003049 } else {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003050 delay = Settings.Global.getInt(mContext.getContentResolver(),
3051 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003052 }
3053 mInetConditionChangeInFlight = true;
3054 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville151eaa62013-01-31 00:30:13 +00003055 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003056 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003057 // we've set the new condition, when this hold ends that will get picked up
3058 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003059 }
3060 }
3061
Wink Saville151eaa62013-01-31 00:30:13 +00003062 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003063 if (DBG) {
Wink Saville151eaa62013-01-31 00:30:13 +00003064 log("handleInetConditionHoldEnd: net=" + netType +
3065 ", condition=" + mDefaultInetCondition +
3066 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003067 }
3068 mInetConditionChangeInFlight = false;
3069
3070 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003071 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003072 return;
3073 }
3074 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003075 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003076 return;
3077 }
Wink Saville151eaa62013-01-31 00:30:13 +00003078 // TODO: Figure out why this optimization sometimes causes a
3079 // change in mDefaultInetCondition to be missed and the
3080 // UI to not be updated.
3081 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3082 // if (DBG) log("no change in condition - aborting");
3083 // return;
3084 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003085 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3086 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003087 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003088 return;
3089 }
Wink Saville151eaa62013-01-31 00:30:13 +00003090 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003091 sendInetConditionBroadcast(networkInfo);
3092 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003093 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003094
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003095 public ProxyProperties getProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003096 // this information is already available as a world read/writable jvm property
3097 // so this API change wouldn't have a benifit. It also breaks the passing
3098 // of proxy info to all the JVMs.
3099 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003100 synchronized (mProxyLock) {
3101 if (mGlobalProxy != null) return mGlobalProxy;
3102 return (mDefaultProxyDisabled ? null : mDefaultProxy);
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003103 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003104 }
3105
3106 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003107 enforceConnectivityInternalPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003108 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003109 if (proxyProperties == mGlobalProxy) return;
3110 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3111 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3112
3113 String host = "";
3114 int port = 0;
3115 String exclList = "";
3116 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3117 mGlobalProxy = new ProxyProperties(proxyProperties);
3118 host = mGlobalProxy.getHost();
3119 port = mGlobalProxy.getPort();
3120 exclList = mGlobalProxy.getExclusionList();
3121 } else {
3122 mGlobalProxy = null;
3123 }
3124 ContentResolver res = mContext.getContentResolver();
Robert Greenwalt6477bd02013-04-10 15:32:18 -07003125 final long token = Binder.clearCallingIdentity();
3126 try {
3127 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3128 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3129 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3130 exclList);
3131 } finally {
3132 Binder.restoreCallingIdentity(token);
3133 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003134 }
3135
3136 if (mGlobalProxy == null) {
3137 proxyProperties = mDefaultProxy;
3138 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003139 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003140 }
3141
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003142 private void loadGlobalProxy() {
3143 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003144 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3145 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3146 String exclList = Settings.Global.getString(res,
3147 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003148 if (!TextUtils.isEmpty(host)) {
3149 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003150 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003151 mGlobalProxy = proxyProperties;
3152 }
3153 }
3154 }
3155
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003156 public ProxyProperties getGlobalProxy() {
Robert Greenwalt0e0ae8a2013-02-22 14:57:00 -08003157 // this information is already available as a world read/writable jvm property
3158 // so this API change wouldn't have a benifit. It also breaks the passing
3159 // of proxy info to all the JVMs.
3160 // enforceAccessPermission();
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003161 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003162 return mGlobalProxy;
3163 }
3164 }
3165
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003166 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3167 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3168 proxy = null;
3169 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003170 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003171 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003172 if (mDefaultProxy == proxy) return; // catches repeated nulls
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003173 mDefaultProxy = proxy;
3174
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003175 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003176 if (!mDefaultProxyDisabled) {
3177 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003178 }
3179 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003180 }
3181
3182 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey8c870452012-09-26 22:03:49 -07003183 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3184 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003185 if (!TextUtils.isEmpty(proxy)) {
3186 String data[] = proxy.split(":");
3187 String proxyHost = data[0];
3188 int proxyPort = 8080;
3189 if (data.length > 1) {
3190 try {
3191 proxyPort = Integer.parseInt(data[1]);
3192 } catch (NumberFormatException e) {
3193 return;
3194 }
3195 }
3196 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3197 setGlobalProxy(p);
3198 }
3199 }
3200
3201 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003202 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07003203 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003204 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003205 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3206 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003207 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003208 final long ident = Binder.clearCallingIdentity();
3209 try {
3210 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3211 } finally {
3212 Binder.restoreCallingIdentity(ident);
3213 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003214 }
3215
3216 private static class SettingsObserver extends ContentObserver {
3217 private int mWhat;
3218 private Handler mHandler;
3219 SettingsObserver(Handler handler, int what) {
3220 super(handler);
3221 mHandler = handler;
3222 mWhat = what;
3223 }
3224
3225 void observe(Context context) {
3226 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey8c870452012-09-26 22:03:49 -07003227 resolver.registerContentObserver(Settings.Global.getUriFor(
3228 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003229 }
3230
3231 @Override
3232 public void onChange(boolean selfChange) {
3233 mHandler.obtainMessage(mWhat).sendToTarget();
3234 }
3235 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003236
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003237 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003238 Slog.d(TAG, s);
3239 }
3240
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003241 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003242 Slog.e(TAG, s);
3243 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003244
repo syncf5de5572011-07-29 23:55:49 -07003245 int convertFeatureToNetworkType(int networkType, String feature) {
3246 int usedNetworkType = networkType;
3247
3248 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3249 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3250 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3251 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3252 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3253 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3254 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3255 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3256 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3257 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3258 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3259 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3260 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3261 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3262 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3263 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3264 } else {
3265 Slog.e(TAG, "Can't match any mobile netTracker!");
3266 }
3267 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3268 if (TextUtils.equals(feature, "p2p")) {
3269 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3270 } else {
3271 Slog.e(TAG, "Can't match any wifi netTracker!");
3272 }
3273 } else {
3274 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003275 }
repo syncf5de5572011-07-29 23:55:49 -07003276 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003277 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003278
3279 private static <T> T checkNotNull(T value, String message) {
3280 if (value == null) {
3281 throw new NullPointerException(message);
3282 }
3283 return value;
3284 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003285
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003286 /**
3287 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003288 * VpnBuilder and not available in ConnectivityManager. Permissions
3289 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003290 * @hide
3291 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003292 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003293 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003294 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003295 try {
3296 int type = mActiveDefaultNetwork;
Robert Greenwalt15a41532012-08-21 19:27:00 -07003297 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003298 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3299 return true;
3300 }
3301 } catch (Exception e) {
3302 // ignore
3303 } finally {
3304 try {
3305 socket.close();
3306 } catch (Exception e) {
3307 // ignore
3308 }
3309 }
3310 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003311 }
3312
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003313 /**
3314 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003315 * and not available in ConnectivityManager. Permissions are checked
3316 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003317 * @hide
3318 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003319 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003320 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003321 throwIfLockdownEnabled();
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003322 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003323 }
3324
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003325 /**
3326 * Configure a TUN interface and return its file descriptor. Parameters
3327 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003328 * and not available in ConnectivityManager. Permissions are checked in
3329 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003330 * @hide
3331 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003332 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003333 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003334 throwIfLockdownEnabled();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003335 return mVpn.establish(config);
3336 }
3337
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003338 /**
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003339 * Start legacy VPN, controlling native daemons as needed. Creates a
3340 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003341 */
3342 @Override
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003343 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003344 throwIfLockdownEnabled();
Jeff Sharkey64d8b3b2012-08-24 11:17:25 -07003345 final LinkProperties egress = getActiveLinkProperties();
3346 if (egress == null) {
3347 throw new IllegalStateException("Missing active network connection");
3348 }
3349 mVpn.startLegacyVpn(profile, mKeyStore, egress);
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003350 }
3351
3352 /**
3353 * Return the information of the ongoing legacy VPN. This method is used
3354 * by VpnSettings and not available in ConnectivityManager. Permissions
3355 * are checked in Vpn class.
3356 * @hide
3357 */
3358 @Override
3359 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003360 throwIfLockdownEnabled();
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003361 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003362 }
3363
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003364 /**
3365 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3366 * through NetworkStateTracker since it works differently. For example, it
3367 * needs to override DNS servers but never takes the default routes. It
3368 * relies on another data network, and it could keep existing connections
3369 * alive after reconnecting, switching between networks, or even resuming
3370 * from deep sleep. Calls from applications should be done synchronously
3371 * to avoid race conditions. As these are all hidden APIs, refactoring can
3372 * be done whenever a better abstraction is developed.
3373 */
3374 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003375 private VpnCallback() {
3376 }
3377
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003378 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003379 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey366e0b72012-08-04 15:24:58 -07003380 }
3381
Chia-chi Yehcc844502011-07-14 18:01:57 -07003382 public void override(List<String> dnsServers, List<String> searchDomains) {
3383 if (dnsServers == null) {
3384 restore();
3385 return;
3386 }
3387
3388 // Convert DNS servers into addresses.
3389 List<InetAddress> addresses = new ArrayList<InetAddress>();
3390 for (String address : dnsServers) {
3391 // Double check the addresses and remove invalid ones.
3392 try {
3393 addresses.add(InetAddress.parseNumericAddress(address));
3394 } catch (Exception e) {
3395 // ignore
3396 }
3397 }
3398 if (addresses.isEmpty()) {
3399 restore();
3400 return;
3401 }
3402
3403 // Concatenate search domains into a string.
3404 StringBuilder buffer = new StringBuilder();
3405 if (searchDomains != null) {
3406 for (String domain : searchDomains) {
3407 buffer.append(domain).append(' ');
3408 }
3409 }
3410 String domains = buffer.toString().trim();
3411
3412 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003413 synchronized (mDnsLock) {
Mattias Falkd697aa22011-08-23 14:15:13 +02003414 updateDnsLocked("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003415 mDnsOverridden = true;
3416 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003417
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003418 // Temporarily disable the default proxy (not global).
3419 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003420 mDefaultProxyDisabled = true;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003421 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003422 sendProxyBroadcast(null);
3423 }
3424 }
3425
3426 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003427 }
3428
Chia-chi Yehcc844502011-07-14 18:01:57 -07003429 public void restore() {
3430 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003431 if (mDnsOverridden) {
3432 mDnsOverridden = false;
3433 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003434 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003435 }
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003436 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003437 mDefaultProxyDisabled = false;
Robert Greenwaltf9661d32013-04-05 17:14:19 -07003438 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003439 sendProxyBroadcast(mDefaultProxy);
3440 }
3441 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003442 }
3443 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003444
3445 @Override
3446 public boolean updateLockdownVpn() {
Jeff Sharkey760c6202013-01-31 17:22:26 -08003447 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3448 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3449 return false;
3450 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003451
3452 // Tear down existing lockdown if profile was removed
3453 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3454 if (mLockdownEnabled) {
Kenny Root0ded63c2013-02-14 10:18:38 -08003455 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003456 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3457 return false;
3458 }
3459
3460 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3461 final VpnProfile profile = VpnProfile.decode(
3462 profileName, mKeyStore.get(Credentials.VPN + profileName));
3463 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3464 } else {
3465 setLockdownTracker(null);
3466 }
3467
3468 return true;
3469 }
3470
3471 /**
3472 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3473 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3474 */
3475 private void setLockdownTracker(LockdownVpnTracker tracker) {
3476 // Shutdown any existing tracker
3477 final LockdownVpnTracker existing = mLockdownTracker;
3478 mLockdownTracker = null;
3479 if (existing != null) {
3480 existing.shutdown();
3481 }
3482
3483 try {
3484 if (tracker != null) {
3485 mNetd.setFirewallEnabled(true);
Jeff Sharkeydb44d2c2013-02-28 16:57:58 -08003486 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003487 mLockdownTracker = tracker;
3488 mLockdownTracker.init();
3489 } else {
3490 mNetd.setFirewallEnabled(false);
3491 }
3492 } catch (RemoteException e) {
3493 // ignored; NMS lives inside system_server
3494 }
3495 }
3496
3497 private void throwIfLockdownEnabled() {
3498 if (mLockdownEnabled) {
3499 throw new IllegalStateException("Unavailable in lockdown mode");
3500 }
3501 }
Robert Greenwalt15a41532012-08-21 19:27:00 -07003502
3503 public void supplyMessenger(int networkType, Messenger messenger) {
3504 enforceConnectivityInternalPermission();
3505
3506 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3507 mNetTrackers[networkType].supplyMessenger(messenger);
3508 }
3509 }
Robert Greenwalt9a37e5d2013-04-22 11:13:02 -07003510
3511 public int findConnectionTypeForIface(String iface) {
3512 enforceConnectivityInternalPermission();
3513
3514 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3515 for (NetworkStateTracker tracker : mNetTrackers) {
3516 if (tracker != null) {
3517 LinkProperties lp = tracker.getLinkProperties();
3518 if (lp != null && iface.equals(lp.getInterfaceName())) {
3519 return tracker.getNetworkInfo().getType();
3520 }
3521 }
3522 }
3523 return ConnectivityManager.TYPE_NONE;
3524 }
Wink Saville32506bc2013-06-29 21:10:57 -07003525
3526 /**
3527 * Have mobile data fail fast if enabled.
3528 *
3529 * @param enabled DctConstants.ENABLED/DISABLED
3530 */
3531 private void setEnableFailFastMobileData(int enabled) {
3532 int tag;
3533
3534 if (enabled == DctConstants.ENABLED) {
3535 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3536 } else {
3537 tag = mEnableFailFastMobileDataTag.get();
3538 }
3539 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3540 enabled));
3541 }
3542
3543 @Override
3544 public int checkMobileProvisioning(boolean sendNotification, int suggestedTimeOutMs,
3545 final ResultReceiver resultReceiver) {
3546 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3547 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3548 + " resultReceiver=" + resultReceiver);
3549 enforceChangePermission();
3550
3551 int timeOutMs = suggestedTimeOutMs;
3552 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3553 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3554 }
3555
3556 final long token = Binder.clearCallingIdentity();
3557 try {
3558 CheckMp checkMp = new CheckMp(mContext, this);
3559 CheckMp.CallBack cb = new CheckMp.CallBack() {
3560 @Override
3561 void onComplete(Integer result) {
3562 log("CheckMp.onComplete: result=" + result);
3563 if (resultReceiver != null) {
3564 log("CheckMp.onComplete: send result");
3565 resultReceiver.send(result, null);
3566 }
3567 NetworkInfo ni =
3568 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3569 switch(result) {
3570 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3571 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3572 log("CheckMp.onComplete: ignore, connected or no connection");
3573 break;
3574 }
3575 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3576 log("CheckMp.onComplete: warm sim");
3577 String url = getProvisioningUrl();
3578 if (TextUtils.isEmpty(url)) {
3579 url = mContext.getResources()
3580 .getString(R.string.mobile_redirected_provisioning_url);
3581 }
3582 if (TextUtils.isEmpty(url) == false) {
3583 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3584 setNotificationVisible(true, ni, url);
3585 } else {
3586 log("CheckMp.onComplete: warm sim (redirected), no url");
3587 }
3588 break;
3589 }
3590 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3591 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
3592 String url = getProvisioningUrl();
3593 if (TextUtils.isEmpty(url) == false) {
3594 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3595 setNotificationVisible(true, ni, url);
3596 } else {
3597 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3598 }
3599 break;
3600 }
3601 default: {
3602 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3603 break;
3604 }
3605 }
3606 }
3607 };
3608 CheckMp.Params params =
3609 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3610 log("checkMobileProvisioning: params=" + params);
3611 setNotificationVisible(false, null, null);
3612 checkMp.execute(params);
3613 } finally {
3614 Binder.restoreCallingIdentity(token);
3615 log("checkMobileProvisioning: X");
3616 }
3617 return timeOutMs;
3618 }
3619
3620 static class CheckMp extends
3621 AsyncTask<CheckMp.Params, Void, Integer> {
3622 private static final String CHECKMP_TAG = "CheckMp";
3623 public static final int MAX_TIMEOUT_MS = 60000;
3624 private static final int SOCKET_TIMEOUT_MS = 5000;
3625 private Context mContext;
3626 private ConnectivityService mCs;
3627 private TelephonyManager mTm;
3628 private Params mParams;
3629
3630 /**
3631 * Parameters for AsyncTask.execute
3632 */
3633 static class Params {
3634 private String mUrl;
3635 private long mTimeOutMs;
3636 private CallBack mCb;
3637
3638 Params(String url, long timeOutMs, CallBack cb) {
3639 mUrl = url;
3640 mTimeOutMs = timeOutMs;
3641 mCb = cb;
3642 }
3643
3644 @Override
3645 public String toString() {
3646 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3647 }
3648 }
3649
3650 /**
3651 * The call back object passed in Params. onComplete will be called
3652 * on the main thread.
3653 */
3654 abstract static class CallBack {
3655 // Called on the main thread.
3656 abstract void onComplete(Integer result);
3657 }
3658
3659 public CheckMp(Context context, ConnectivityService cs) {
3660 mContext = context;
3661 mCs = cs;
3662
3663 // Setup access to TelephonyService we'll be using.
3664 mTm = (TelephonyManager) mContext.getSystemService(
3665 Context.TELEPHONY_SERVICE);
3666 }
3667
3668 /**
3669 * Get the default url to use for the test.
3670 */
3671 public String getDefaultUrl() {
3672 // See http://go/clientsdns for usage approval
3673 String server = Settings.Global.getString(mContext.getContentResolver(),
3674 Settings.Global.CAPTIVE_PORTAL_SERVER);
3675 if (server == null) {
3676 server = "clients3.google.com";
3677 }
3678 return "http://" + server + "/generate_204";
3679 }
3680
3681 /**
3682 * Detect if its possible to connect to the http url. DNS based detection techniques
3683 * do not work at all hotspots. The best way to check is to perform a request to
3684 * a known address that fetches the data we expect.
3685 */
3686 private synchronized Integer isMobileOk(Params params) {
3687 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3688 Uri orgUri = Uri.parse(params.mUrl);
3689 Random rand = new Random();
3690 mParams = params;
3691
3692 try {
3693 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3694 log("isMobileOk: not mobile capable");
3695 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3696 return result;
3697 }
3698
3699 // Enable fail fast as we'll do retries here and use a
3700 // hipri connection so the default connection stays active.
3701 log("isMobileOk: start hipri url=" + params.mUrl);
3702 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3703 mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3704 Phone.FEATURE_ENABLE_HIPRI, new Binder());
3705
3706 // Continue trying to connect until time has run out
3707 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3708 while(SystemClock.elapsedRealtime() < endTime) {
3709 try {
3710 // Wait for hipri to connect.
3711 // TODO: Don't poll and handle situation where hipri fails
3712 // because default is retrying. See b/9569540
3713 NetworkInfo.State state = mCs
3714 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3715 if (state != NetworkInfo.State.CONNECTED) {
3716 log("isMobileOk: not connected ni=" +
3717 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3718 sleep(1);
3719 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3720 continue;
3721 }
3722
3723 // Get of the addresses associated with the url host. We need to use the
3724 // address otherwise HttpURLConnection object will use the name to get
3725 // the addresses and is will try every address but that will bypass the
3726 // route to host we setup and the connection could succeed as the default
3727 // interface might be connected to the internet via wifi or other interface.
3728 InetAddress[] addresses;
3729 try {
3730 addresses = InetAddress.getAllByName(orgUri.getHost());
3731 } catch (UnknownHostException e) {
3732 log("isMobileOk: UnknownHostException");
3733 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3734 return result;
3735 }
3736 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3737
3738 // Get the type of addresses supported by this link
3739 LinkProperties lp = mCs.getLinkProperties(
3740 ConnectivityManager.TYPE_MOBILE_HIPRI);
3741 boolean linkHasIpv4 = hasIPv4Address(lp);
3742 boolean linkHasIpv6 = hasIPv6Address(lp);
3743 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3744 + " linkHasIpv6=" + linkHasIpv6);
3745
3746 // Loop through at most 3 valid addresses or all of the address or until
3747 // we run out of time
3748 int loops = Math.min(3, addresses.length);
3749 for(int validAddr=0, addrTried=0;
3750 (validAddr < loops) && (addrTried < addresses.length)
3751 && (SystemClock.elapsedRealtime() < endTime);
3752 addrTried ++) {
3753
3754 // Choose the address at random but make sure its type is supported
3755 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3756 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3757 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3758 // Valid address, so use it
3759 validAddr += 1;
3760 } else {
3761 // Invalid address so try next address
3762 continue;
3763 }
3764
3765 // Make a route to host so we check the specific interface.
3766 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3767 hostAddr.getAddress())) {
3768 // Wait a short time to be sure the route is established ??
3769 log("isMobileOk:"
3770 + " wait to establish route to hostAddr=" + hostAddr);
3771 sleep(3);
3772 } else {
3773 log("isMobileOk:"
3774 + " could not establish route to hostAddr=" + hostAddr);
3775 continue;
3776 }
3777
3778 // Rewrite the url to have numeric address to use the specific route.
3779 // I also set the "Connection" to "Close" as by default "Keep-Alive"
3780 // is used which is useless in this case.
3781 URL newUrl = new URL(orgUri.getScheme() + "://"
3782 + hostAddr.getHostAddress() + orgUri.getPath());
3783 log("isMobileOk: newUrl=" + newUrl);
3784
3785 HttpURLConnection urlConn = null;
3786 try {
3787 // Open the connection set the request header and get the response
3788 urlConn = (HttpURLConnection) newUrl.openConnection(
3789 java.net.Proxy.NO_PROXY);
3790 urlConn.setInstanceFollowRedirects(false);
3791 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3792 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3793 urlConn.setUseCaches(false);
3794 urlConn.setAllowUserInteraction(false);
3795 urlConn.setRequestProperty("Connection", "close");
3796 int responseCode = urlConn.getResponseCode();
3797 if (responseCode == 204) {
3798 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
3799 } else {
3800 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3801 }
3802 log("isMobileOk: connected responseCode=" + responseCode);
3803 urlConn.disconnect();
3804 urlConn = null;
3805 return result;
3806 } catch (Exception e) {
3807 log("isMobileOk: HttpURLConnection Exception e=" + e);
3808 if (urlConn != null) {
3809 urlConn.disconnect();
3810 urlConn = null;
3811 }
3812 }
3813 }
3814 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3815 log("isMobileOk: loops|timed out");
3816 return result;
3817 } catch (Exception e) {
3818 log("isMobileOk: Exception e=" + e);
3819 continue;
3820 }
3821 }
3822 log("isMobileOk: timed out");
3823 } finally {
3824 log("isMobileOk: F stop hipri");
3825 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3826 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3827 Phone.FEATURE_ENABLE_HIPRI);
3828 log("isMobileOk: X result=" + result);
3829 }
3830 return result;
3831 }
3832
3833 @Override
3834 protected Integer doInBackground(Params... params) {
3835 return isMobileOk(params[0]);
3836 }
3837
3838 @Override
3839 protected void onPostExecute(Integer result) {
3840 log("onPostExecute: result=" + result);
3841 if ((mParams != null) && (mParams.mCb != null)) {
3842 mParams.mCb.onComplete(result);
3843 }
3844 }
3845
3846 private String inetAddressesToString(InetAddress[] addresses) {
3847 StringBuffer sb = new StringBuffer();
3848 boolean firstTime = true;
3849 for(InetAddress addr : addresses) {
3850 if (firstTime) {
3851 firstTime = false;
3852 } else {
3853 sb.append(",");
3854 }
3855 sb.append(addr);
3856 }
3857 return sb.toString();
3858 }
3859
3860 private void printNetworkInfo() {
3861 boolean hasIccCard = mTm.hasIccCard();
3862 int simState = mTm.getSimState();
3863 log("hasIccCard=" + hasIccCard
3864 + " simState=" + simState);
3865 NetworkInfo[] ni = mCs.getAllNetworkInfo();
3866 if (ni != null) {
3867 log("ni.length=" + ni.length);
3868 for (NetworkInfo netInfo: ni) {
3869 log("netInfo=" + netInfo.toString());
3870 }
3871 } else {
3872 log("no network info ni=null");
3873 }
3874 }
3875
3876 /**
3877 * Sleep for a few seconds then return.
3878 * @param seconds
3879 */
3880 private static void sleep(int seconds) {
3881 try {
3882 Thread.sleep(seconds * 1000);
3883 } catch (InterruptedException e) {
3884 e.printStackTrace();
3885 }
3886 }
3887
3888 public boolean hasIPv4Address(LinkProperties lp) {
3889 return lp.hasIPv4Address();
3890 }
3891
3892 // Not implemented in LinkProperties, do it here.
3893 public boolean hasIPv6Address(LinkProperties lp) {
3894 for (LinkAddress address : lp.getLinkAddresses()) {
3895 if (address.getAddress() instanceof Inet6Address) {
3896 return true;
3897 }
3898 }
3899 return false;
3900 }
3901
3902 private void log(String s) {
3903 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
3904 }
3905 }
3906
3907 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3908
3909 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
3910 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
3911
3912 Resources r = Resources.getSystem();
3913 NotificationManager notificationManager = (NotificationManager) mContext
3914 .getSystemService(Context.NOTIFICATION_SERVICE);
3915
3916 if (visible) {
3917 CharSequence title;
3918 CharSequence details;
3919 int icon;
3920 switch (networkInfo.getType()) {
3921 case ConnectivityManager.TYPE_WIFI:
3922 log("setNotificationVisible: TYPE_WIFI");
3923 title = r.getString(R.string.wifi_available_sign_in, 0);
3924 details = r.getString(R.string.network_available_sign_in_detailed,
3925 networkInfo.getExtraInfo());
3926 icon = R.drawable.stat_notify_wifi_in_range;
3927 break;
3928 case ConnectivityManager.TYPE_MOBILE:
3929 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3930 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
3931 title = r.getString(R.string.network_available_sign_in, 0);
3932 // TODO: Change this to pull from NetworkInfo once a printable
3933 // name has been added to it
3934 details = mTelephonyManager.getNetworkOperatorName();
3935 icon = R.drawable.stat_notify_rssi_in_range;
3936 break;
3937 default:
3938 log("setNotificationVisible: other type=" + networkInfo.getType());
3939 title = r.getString(R.string.network_available_sign_in, 0);
3940 details = r.getString(R.string.network_available_sign_in_detailed,
3941 networkInfo.getExtraInfo());
3942 icon = R.drawable.stat_notify_rssi_in_range;
3943 break;
3944 }
3945
3946 Notification notification = new Notification();
3947 notification.when = 0;
3948 notification.icon = icon;
3949 notification.flags = Notification.FLAG_AUTO_CANCEL;
3950 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
3951 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3952 Intent.FLAG_ACTIVITY_NEW_TASK);
3953 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
3954 notification.tickerText = title;
3955 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
3956
3957 log("setNotificaitionVisible: notify notificaiton=" + notification);
3958 notificationManager.notify(NOTIFICATION_ID, 1, notification);
3959 } else {
3960 log("setNotificaitionVisible: cancel");
3961 notificationManager.cancel(NOTIFICATION_ID, 1);
3962 }
3963 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
3964 }
3965
3966 private String getProvisioningUrl() {
3967 String url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3968 log("getProvisioningUrl: resource url=" + url);
3969
3970 // populate the iccid and imei in the provisioning url.
3971 if (!TextUtils.isEmpty(url)) {
3972 url = String.format(url,
3973 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3974 mTelephonyManager.getDeviceId() /* IMEI */,
3975 mTelephonyManager.getLine1Number() /* Phone numer */);
3976 }
3977
3978 log("getProvisioningUrl: url=" + url);
3979 return url;
3980 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003981}