blob: 8c388edb149e3f2d225ff093a4ca35587d8f0499 [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 Saville690cb182013-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 Sharkeyf2e722a2012-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 Sharkeyf2e722a2012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project28527d22009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -070045import android.content.res.Configuration;
tk.mun093f55c2011-10-13 22:51:57 +090046import android.content.res.Resources;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070047import android.database.ContentObserver;
Irfan Sheriffba8388b2012-08-16 12:49:23 -070048import android.net.CaptivePortalTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Robert Greenwalteb123ac2010-12-06 13:56:24 -080050import android.net.DummyDataStateTracker;
Benoit Goby211b5692010-12-22 14:29:40 -080051import android.net.EthernetDataTracker;
The Android Open Source Project28527d22009-03-03 19:31:44 -080052import android.net.IConnectivityManager;
Haoyu Baib5da5752012-06-20 14:29:57 -070053import android.net.INetworkManagementEventObserver;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070054import android.net.INetworkPolicyListener;
55import android.net.INetworkPolicyManager;
Jeff Sharkeyb6188a12011-09-22 14:59:51 -070056import android.net.INetworkStatsService;
Wink Savilledc5d1ba2011-07-14 12:23:28 -070057import android.net.LinkAddress;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -080058import android.net.LinkProperties;
Wink Saville690cb182013-06-29 21:10:57 -070059import android.net.Uri;
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -070060import android.net.LinkProperties.CompareResult;
The Android Open Source Project28527d22009-03-03 19:31:44 -080061import android.net.MobileDataStateTracker;
Robert Greenwalt34848c02011-03-25 13:09:25 -070062import android.net.NetworkConfig;
The Android Open Source Project28527d22009-03-03 19:31:44 -080063import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070064import android.net.NetworkInfo.DetailedState;
Wink Saville690cb182013-06-29 21:10:57 -070065import android.net.NetworkInfo.State;
Jeff Sharkey66fa9682011-08-02 17:22:34 -070066import android.net.NetworkQuotaInfo;
Jeff Sharkey21062e72011-05-28 20:56:34 -070067import android.net.NetworkState;
The Android Open Source Project28527d22009-03-03 19:31:44 -080068import android.net.NetworkStateTracker;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -070069import android.net.NetworkUtils;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -070070import android.net.Proxy;
71import android.net.ProxyProperties;
Robert Greenwalt5a901292011-04-28 14:28:50 -070072import android.net.RouteInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -080073import android.net.wifi.WifiStateTracker;
tk.mun093f55c2011-10-13 22:51:57 +090074import android.net.wimax.WimaxManagerConstants;
Wink Saville690cb182013-06-29 21:10:57 -070075import android.os.AsyncTask;
The Android Open Source Project28527d22009-03-03 19:31:44 -080076import android.os.Binder;
Mike Lockwood0d5916c2011-05-28 13:24:04 -040077import android.os.FileUtils;
The Android Open Source Project28527d22009-03-03 19:31:44 -080078import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -070079import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -070080import android.os.IBinder;
Chia-chi Yeh4df51322011-05-11 16:35:13 -070081import android.os.INetworkManagementService;
The Android Open Source Project28527d22009-03-03 19:31:44 -080082import android.os.Looper;
83import android.os.Message;
Robert Greenwalt030e1d32012-08-21 19:27:00 -070084import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -070085import android.os.ParcelFileDescriptor;
Robert Greenwalt93dc1042010-06-15 12:19:37 -070086import android.os.PowerManager;
Jeff Sharkey5663b6e2012-09-06 17:54:29 -070087import android.os.Process;
Robert Greenwalt2034b912009-08-12 16:08:25 -070088import android.os.RemoteException;
Wink Saville690cb182013-06-29 21:10:57 -070089import android.os.ResultReceiver;
The Android Open Source Project28527d22009-03-03 19:31:44 -080090import android.os.ServiceManager;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -070091import android.os.SystemClock;
The Android Open Source Project28527d22009-03-03 19:31:44 -080092import android.os.SystemProperties;
Dianne Hackbornbc55bd12012-08-29 18:32:08 -070093import android.os.UserHandle;
The Android Open Source Project28527d22009-03-03 19:31:44 -080094import android.provider.Settings;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -070095import android.security.Credentials;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -070096import android.security.KeyStore;
Wink Saville690cb182013-06-29 21:10:57 -070097import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -070098import android.text.TextUtils;
Joe Onoratoc2386bb2010-02-26 18:56:32 -080099import android.util.Slog;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700100import android.util.SparseIntArray;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700101import android.util.Xml;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800102
Wink Saville690cb182013-06-29 21:10:57 -0700103import com.android.internal.R;
Chia-chi Yehbded3eb2011-07-04 03:23:12 -0700104import com.android.internal.net.LegacyVpnInfo;
Chia-chi Yeh75cacd52011-06-15 17:07:27 -0700105import com.android.internal.net.VpnConfig;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700106import com.android.internal.net.VpnProfile;
Wink Saville690cb182013-06-29 21:10:57 -0700107import com.android.internal.telephony.DctConstants;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700108import com.android.internal.telephony.Phone;
Wink Saville64e3f782012-07-10 12:37:54 -0700109import com.android.internal.telephony.PhoneConstants;
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -0700110import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700111import com.android.internal.util.XmlUtils;
Jeff Sharkeyaac2c502011-10-04 16:54:49 -0700112import com.android.server.am.BatteryStatsService;
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900113import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800114import com.android.server.connectivity.Tethering;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700115import com.android.server.connectivity.Vpn;
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -0700116import com.android.server.net.BaseNetworkObserver;
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700117import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700118import com.google.android.collect.Lists;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700119import com.google.android.collect.Sets;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700120
tk.mun093f55c2011-10-13 22:51:57 +0900121import dalvik.system.DexClassLoader;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700122
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700123import org.xmlpull.v1.XmlPullParser;
124import org.xmlpull.v1.XmlPullParserException;
125
126import java.io.File;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800127import java.io.FileDescriptor;
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -0700128import java.io.FileNotFoundException;
129import java.io.FileReader;
Irfan Sheriff7f132d92010-06-09 15:39:36 -0700130import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800131import java.io.PrintWriter;
tk.mun093f55c2011-10-13 22:51:57 +0900132import java.lang.reflect.Constructor;
Wink Saville690cb182013-06-29 21:10:57 -0700133import java.net.HttpURLConnection;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700134import java.net.Inet4Address;
Wink Saville051a6642011-07-13 13:44:13 -0700135import java.net.Inet6Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700136import java.net.InetAddress;
Wink Saville690cb182013-06-29 21:10:57 -0700137import java.net.URL;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700138import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700139import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700140import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700141import java.util.Collection;
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700142import java.util.GregorianCalendar;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700143import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700144import java.util.List;
Wink Saville690cb182013-06-29 21:10:57 -0700145import java.util.Random;
146import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800147
148/**
149 * @hide
150 */
151public class ConnectivityService extends IConnectivityManager.Stub {
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700152 private static final String TAG = "ConnectivityService";
The Android Open Source Project28527d22009-03-03 19:31:44 -0800153
Robert Greenwalt063dc7d2010-10-05 19:12:26 -0700154 private static final boolean DBG = true;
Wink Savillea7d56572011-09-21 11:05:43 -0700155 private static final boolean VDBG = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800156
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700157 private static final boolean LOGD_RULES = false;
158
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700159 // TODO: create better separation between radio types and network types
160
Robert Greenwalt2034b912009-08-12 16:08:25 -0700161 // how long to wait before switching back to a radio's default network
162 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
163 // system property that can override the above value
164 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
165 "android.telephony.apn-restore";
166
Wink Saville690cb182013-06-29 21:10:57 -0700167 // Default value if FAIL_FAST_TIME_MS is not set
168 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
169 // system property that can override DEFAULT_FAIL_FAST_TIME_MS
170 private static final String FAIL_FAST_TIME_MS =
171 "persist.radio.fail_fast_time_ms";
172
Robert Greenwaltbd492212011-05-06 17:10:53 -0700173 // used in recursive route setting to add gateways for the host for which
174 // a host route was requested.
175 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
176
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800177 private Tethering mTethering;
178
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700179 private KeyStore mKeyStore;
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700180
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700181 private Vpn mVpn;
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700182 private VpnCallback mVpnCallback = new VpnCallback();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700183
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700184 private boolean mLockdownEnabled;
185 private LockdownVpnTracker mLockdownTracker;
186
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900187 private Nat464Xlat mClat;
188
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700189 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
190 private Object mRulesLock = new Object();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700191 /** Currently active network rules by UID. */
192 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700193 /** Set of ifaces that are costly. */
194 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700195
The Android Open Source Project28527d22009-03-03 19:31:44 -0800196 /**
197 * Sometimes we want to refer to the individual network state
198 * trackers separately, and sometimes we just want to treat them
199 * abstractly.
200 */
201 private NetworkStateTracker mNetTrackers[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700202
Irfan Sheriffba8388b2012-08-16 12:49:23 -0700203 /* Handles captive portal check on a network */
204 private CaptivePortalTracker mCaptivePortalTracker;
205
Robert Greenwalt2034b912009-08-12 16:08:25 -0700206 /**
Wink Saville051a6642011-07-13 13:44:13 -0700207 * The link properties that define the current links
208 */
209 private LinkProperties mCurrentLinkProperties[];
210
211 /**
Robert Greenwalt2034b912009-08-12 16:08:25 -0700212 * A per Net list of the PID's that requested access to the net
213 * used both as a refcount and for per-PID DNS selection
214 */
Mattias Falkdc919012011-08-23 14:15:13 +0200215 private List<Integer> mNetRequestersPids[];
Robert Greenwalt2034b912009-08-12 16:08:25 -0700216
Robert Greenwalt2034b912009-08-12 16:08:25 -0700217 // priority order of the nettrackers
218 // (excluding dynamically set mNetworkPreference)
219 // TODO - move mNetworkTypePreference into this
220 private int[] mPriorityList;
221
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222 private Context mContext;
223 private int mNetworkPreference;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700224 private int mActiveDefaultNetwork = -1;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700225 // 0 is full bad, 100 is full good
Wink Saville3e866722013-01-31 00:30:13 +0000226 private int mDefaultInetCondition = 0;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700227 private int mDefaultInetConditionPublished = 0;
228 private boolean mInetConditionChangeInFlight = false;
229 private int mDefaultConnectionSequence = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800230
Chia-chi Yehcc844502011-07-14 18:01:57 -0700231 private Object mDnsLock = new Object();
Robert Greenwaltd44340d2013-02-11 15:25:10 -0800232 private int mNumDnsEntries;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700233 private boolean mDnsOverridden = false;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800234
235 private boolean mTestMode;
Joe Onorato56023ad2010-09-01 21:18:22 -0700236 private static ConnectivityService sServiceInstance;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800237
Robert Greenwalt355205c2011-05-10 15:05:02 -0700238 private INetworkManagementService mNetd;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700239 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700240
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700241 private static final int ENABLED = 1;
242 private static final int DISABLED = 0;
243
Robert Greenwalt49c75d32011-11-02 14:37:19 -0700244 private static final boolean ADD = true;
245 private static final boolean REMOVE = false;
246
247 private static final boolean TO_DEFAULT_TABLE = true;
248 private static final boolean TO_SECONDARY_TABLE = false;
249
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700250 /**
251 * used internally as a delayed event to make us switch back to the
252 * default network
253 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700254 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700255
256 /**
257 * used internally to change our mobile data enabled flag
258 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700259 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700260
261 /**
262 * used internally to change our network preference setting
263 * arg1 = networkType to prefer
264 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700265 private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700266
267 /**
268 * used internally to synchronize inet condition reports
269 * arg1 = networkType
270 * arg2 = condition (0 bad, 100 good)
271 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700272 private static final int EVENT_INET_CONDITION_CHANGE = 4;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700273
274 /**
275 * used internally to mark the end of inet condition hold periods
276 * arg1 = networkType
277 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700278 private static final int EVENT_INET_CONDITION_HOLD_END = 5;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700279
280 /**
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700281 * used internally to set enable/disable cellular data
282 * arg1 = ENBALED or DISABLED
283 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700284 private static final int EVENT_SET_MOBILE_DATA = 7;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700285
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700286 /**
287 * used internally to clear a wakelock when transitioning
288 * from one net to another
289 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700290 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700291
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700292 /**
293 * used internally to reload global proxy settings
294 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700295 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700296
Robert Greenwalt34848c02011-03-25 13:09:25 -0700297 /**
298 * used internally to set external dependency met/unmet
299 * arg1 = ENABLED (met) or DISABLED (unmet)
300 * arg2 = NetworkType
301 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700302 private static final int EVENT_SET_DEPENDENCY_MET = 10;
Robert Greenwalt34848c02011-03-25 13:09:25 -0700303
Chia-chi Yehcc844502011-07-14 18:01:57 -0700304 /**
305 * used internally to restore DNS properties back to the
306 * default network
307 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700308 private static final int EVENT_RESTORE_DNS = 11;
Chia-chi Yehcc844502011-07-14 18:01:57 -0700309
Wink Saville7e4333c2011-08-05 11:40:22 -0700310 /**
Wink Saville4f0de1e2011-08-04 15:01:58 -0700311 * used internally to send a sticky broadcast delayed.
312 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700313 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
Wink Saville4f0de1e2011-08-04 15:01:58 -0700314
Jeff Sharkey805662d2011-08-19 02:24:24 -0700315 /**
316 * Used internally to
317 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
318 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700319 private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
Jeff Sharkey805662d2011-08-19 02:24:24 -0700320
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700321 private static final int EVENT_VPN_STATE_CHANGED = 14;
322
Wink Saville690cb182013-06-29 21:10:57 -0700323 /**
324 * Used internally to disable fail fast of mobile data
325 */
326 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 15;
327
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700328 /** Handler used for internal events. */
329 private InternalHandler mHandler;
330 /** Handler used for incoming {@link NetworkStateTracker} events. */
331 private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700332
333 // list of DeathRecipients used to make sure features are turned off when
334 // a process dies
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500335 private List<FeatureUser> mFeatureUsers;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700336
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400337 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800338 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400339
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700340 private PowerManager.WakeLock mNetTransitionWakeLock;
341 private String mNetTransitionWakeLockCausedBy = "";
342 private int mNetTransitionWakeLockSerialNumber;
343 private int mNetTransitionWakeLockTimeout;
344
Robert Greenwalt94daa182010-09-01 11:34:05 -0700345 private InetAddress mDefaultDns;
346
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -0700347 // this collection is used to refcount the added routes - if there are none left
348 // it's time to remove the route from the route table
349 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
350
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700351 // used in DBG mode to track inet condition reports
352 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
353 private ArrayList mInetLog;
354
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700355 // track the current default http proxy - tell the world if we get a new one (real change)
356 private ProxyProperties mDefaultProxy = null;
Robert Greenwaltda77cb12013-04-05 17:14:19 -0700357 private Object mProxyLock = new Object();
Chia-chi Yeh763a11c2011-10-03 15:34:04 -0700358 private boolean mDefaultProxyDisabled = false;
359
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700360 // track the global proxy.
361 private ProxyProperties mGlobalProxy = null;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700362
363 private SettingsObserver mSettingsObserver;
364
Robert Greenwalt34848c02011-03-25 13:09:25 -0700365 NetworkConfig[] mNetConfigs;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700366 int mNetworksDefined;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700367
Robert Greenwalt12c44552009-12-07 11:33:18 -0800368 private static class RadioAttributes {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700369 public int mSimultaneity;
370 public int mType;
371 public RadioAttributes(String init) {
372 String fragments[] = init.split(",");
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700373 mType = Integer.parseInt(fragments[0]);
374 mSimultaneity = Integer.parseInt(fragments[1]);
Robert Greenwalt2034b912009-08-12 16:08:25 -0700375 }
376 }
377 RadioAttributes[] mRadioAttributes;
378
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700379 // the set of network types that can only be enabled by system/sig apps
380 List mProtectedNetworks;
381
Wink Saville690cb182013-06-29 21:10:57 -0700382 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
383
384 TelephonyManager mTelephonyManager;
385
Wink Saville9564f2b2013-07-16 17:16:37 -0700386 // We only want one checkMobileProvisioning after booting.
387 volatile boolean mFirstProvisioningCheckStarted = false;
388
Jeff Sharkeyb6188a12011-09-22 14:59:51 -0700389 public ConnectivityService(Context context, INetworkManagementService netd,
390 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700391 // Currently, omitting a NetworkFactory will create one internally
392 // TODO: create here when we have cleaner WiMAX support
393 this(context, netd, statsService, policyManager, null);
394 }
395
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700396 public ConnectivityService(Context context, INetworkManagementService netManager,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700397 INetworkStatsService statsService, INetworkPolicyManager policyManager,
398 NetworkFactory netFactory) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800399 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800400
Wink Saville775aad62010-09-02 19:23:52 -0700401 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
402 handlerThread.start();
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700403 mHandler = new InternalHandler(handlerThread.getLooper());
404 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -0700405
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700406 if (netFactory == null) {
407 netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
408 }
409
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800410 // setup our unique device name
Robert Greenwalt82cde132010-12-06 09:30:17 -0800411 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
412 String id = Settings.Secure.getString(context.getContentResolver(),
413 Settings.Secure.ANDROID_ID);
414 if (id != null && id.length() > 0) {
Irfan Sheriff4aa0b2e2011-09-20 15:17:07 -0700415 String name = new String("android-").concat(id);
Robert Greenwalt82cde132010-12-06 09:30:17 -0800416 SystemProperties.set("net.hostname", name);
417 }
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -0800418 }
419
Robert Greenwalt94daa182010-09-01 11:34:05 -0700420 // read our default dns server ip
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700421 String dns = Settings.Global.getString(context.getContentResolver(),
422 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700423 if (dns == null || dns.length() == 0) {
424 dns = context.getResources().getString(
425 com.android.internal.R.string.config_default_dns_server);
426 }
427 try {
Robert Greenwalt35e34d12011-02-22 16:00:42 -0800428 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
429 } catch (IllegalArgumentException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800430 loge("Error setting defaultDns using " + dns);
Robert Greenwalt94daa182010-09-01 11:34:05 -0700431 }
432
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700433 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700434 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700435 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -0700436 mKeyStore = KeyStore.getInstance();
Wink Saville690cb182013-06-29 21:10:57 -0700437 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700438
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700439 try {
440 mPolicyManager.registerListener(mPolicyListener);
441 } catch (RemoteException e) {
442 // ouch, no rules updates means some processes may never get network
Robert Greenwalt78f28112011-08-02 17:18:41 -0700443 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700444 }
445
446 final PowerManager powerManager = (PowerManager) context.getSystemService(
447 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700448 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
449 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
450 com.android.internal.R.integer.config_networkTransitionTimeout);
451
Robert Greenwalt2034b912009-08-12 16:08:25 -0700452 mNetTrackers = new NetworkStateTracker[
453 ConnectivityManager.MAX_NETWORK_TYPE+1];
Wink Saville051a6642011-07-13 13:44:13 -0700454 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt0659da32009-07-16 17:21:39 -0700455
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700456 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
Robert Greenwalt34848c02011-03-25 13:09:25 -0700457 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700458
Robert Greenwalt2034b912009-08-12 16:08:25 -0700459 // Load device network attributes from resources
Robert Greenwalt2034b912009-08-12 16:08:25 -0700460 String[] raStrings = context.getResources().getStringArray(
461 com.android.internal.R.array.radioAttributes);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700462 for (String raString : raStrings) {
463 RadioAttributes r = new RadioAttributes(raString);
464 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800465 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700466 continue;
467 }
468 if (mRadioAttributes[r.mType] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800469 loge("Error in radioAttributes - ignoring attempt to redefine type " +
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700470 r.mType);
471 continue;
472 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700473 mRadioAttributes[r.mType] = r;
474 }
475
Wink Saville23ee8db2013-04-23 14:26:51 -0700476 // TODO: What is the "correct" way to do determine if this is a wifi only device?
477 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
478 log("wifiOnly=" + wifiOnly);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700479 String[] naStrings = context.getResources().getStringArray(
480 com.android.internal.R.array.networkAttributes);
481 for (String naString : naStrings) {
482 try {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700483 NetworkConfig n = new NetworkConfig(naString);
Wink Savillef2a62832011-04-07 14:23:45 -0700484 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800485 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700486 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700487 continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700488 }
Wink Saville23ee8db2013-04-23 14:26:51 -0700489 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
490 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
491 n.type);
492 continue;
493 }
Wink Savillef2a62832011-04-07 14:23:45 -0700494 if (mNetConfigs[n.type] != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800495 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Savillef2a62832011-04-07 14:23:45 -0700496 n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700497 continue;
498 }
Wink Savillef2a62832011-04-07 14:23:45 -0700499 if (mRadioAttributes[n.radio] == null) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800500 loge("Error in networkAttributes - ignoring attempt to use undefined " +
Wink Savillef2a62832011-04-07 14:23:45 -0700501 "radio " + n.radio + " in network type " + n.type);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700502 continue;
503 }
Wink Savillef2a62832011-04-07 14:23:45 -0700504 mNetConfigs[n.type] = n;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700505 mNetworksDefined++;
506 } catch(Exception e) {
507 // ignore it - leave the entry null
Robert Greenwalt2034b912009-08-12 16:08:25 -0700508 }
509 }
510
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700511 mProtectedNetworks = new ArrayList<Integer>();
512 int[] protectedNetworks = context.getResources().getIntArray(
513 com.android.internal.R.array.config_protectedNetworks);
514 for (int p : protectedNetworks) {
515 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
516 mProtectedNetworks.add(p);
517 } else {
518 if (DBG) loge("Ignoring protectedNetwork " + p);
519 }
520 }
521
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700522 // high priority first
523 mPriorityList = new int[mNetworksDefined];
524 {
525 int insertionPoint = mNetworksDefined-1;
526 int currentLowest = 0;
527 int nextLowest = 0;
528 while (insertionPoint > -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -0700529 for (NetworkConfig na : mNetConfigs) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700530 if (na == null) continue;
Wink Savillef2a62832011-04-07 14:23:45 -0700531 if (na.priority < currentLowest) continue;
532 if (na.priority > currentLowest) {
533 if (na.priority < nextLowest || nextLowest == 0) {
534 nextLowest = na.priority;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700535 }
536 continue;
537 }
Wink Savillef2a62832011-04-07 14:23:45 -0700538 mPriorityList[insertionPoint--] = na.type;
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700539 }
540 currentLowest = nextLowest;
541 nextLowest = 0;
542 }
543 }
544
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800545 // Update mNetworkPreference according to user mannually first then overlay config.xml
546 mNetworkPreference = getPersistedNetworkPreference();
547 if (mNetworkPreference == -1) {
548 for (int n : mPriorityList) {
549 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
550 mNetworkPreference = n;
551 break;
552 }
553 }
554 if (mNetworkPreference == -1) {
555 throw new IllegalStateException(
556 "You should set at least one default Network in config.xml!");
557 }
558 }
559
Mattias Falkdc919012011-08-23 14:15:13 +0200560 mNetRequestersPids =
561 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700562 for (int i : mPriorityList) {
Mattias Falkdc919012011-08-23 14:15:13 +0200563 mNetRequestersPids[i] = new ArrayList<Integer>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700564 }
565
Kazuhiro Ondocae18f12011-07-19 11:23:37 -0500566 mFeatureUsers = new ArrayList<FeatureUser>();
Robert Greenwalt2034b912009-08-12 16:08:25 -0700567
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700568 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
569 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700570
571 // Create and start trackers for hard-coded networks
572 for (int targetNetworkType : mPriorityList) {
573 final NetworkConfig config = mNetConfigs[targetNetworkType];
574 final NetworkStateTracker tracker;
575 try {
576 tracker = netFactory.createTracker(targetNetworkType, config);
577 mNetTrackers[targetNetworkType] = tracker;
578 } catch (IllegalArgumentException e) {
579 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
580 + " tracker: " + e);
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700581 continue;
582 }
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700583
584 tracker.startMonitoring(context, mTrackerHandler);
585 if (config.isDefault()) {
586 tracker.reconnect();
Robert Greenwaltcafd8582011-11-10 16:55:20 -0800587 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700588 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -0800589
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700590 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
Robert Greenwaltf1b66e12010-02-25 12:29:30 -0800591
Robert Greenwalt308b9ac2013-04-22 11:13:02 -0700592 mVpn = new Vpn(mContext, mVpnCallback, mNetd, this);
Jeff Sharkey02e14d92012-08-04 15:24:58 -0700593 mVpn.startMonitoring(mContext, mTrackerHandler);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700594
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900595 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
596
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700597 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700598 mNetd.registerObserver(mTethering);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700599 mNetd.registerObserver(mDataActivityObserver);
Lorenzo Colitti5355abd2013-03-15 04:22:37 +0900600 mNetd.registerObserver(mClat);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -0700601 } catch (RemoteException e) {
602 loge("Error registering observer :" + e);
603 }
604
Robert Greenwalt0e80be12010-09-20 14:35:25 -0700605 if (DBG) {
606 mInetLog = new ArrayList();
607 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700608
609 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
610 mSettingsObserver.observe(mContext);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800611
Irfan Sheriff2e617a72012-09-20 09:32:41 -0700612 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -0800613 loadGlobalProxy();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800614 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700615
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700616 /**
617 * Factory that creates {@link NetworkStateTracker} instances using given
618 * {@link NetworkConfig}.
619 */
620 public interface NetworkFactory {
621 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
622 }
623
624 private static class DefaultNetworkFactory implements NetworkFactory {
625 private final Context mContext;
626 private final Handler mTrackerHandler;
627
628 public DefaultNetworkFactory(Context context, Handler trackerHandler) {
629 mContext = context;
630 mTrackerHandler = trackerHandler;
631 }
632
633 @Override
634 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
635 switch (config.radio) {
636 case TYPE_WIFI:
637 return new WifiStateTracker(targetNetworkType, config.name);
638 case TYPE_MOBILE:
639 return new MobileDataStateTracker(targetNetworkType, config.name);
640 case TYPE_DUMMY:
641 return new DummyDataStateTracker(targetNetworkType, config.name);
642 case TYPE_BLUETOOTH:
643 return BluetoothTetheringDataTracker.getInstance();
644 case TYPE_WIMAX:
645 return makeWimaxStateTracker(mContext, mTrackerHandler);
646 case TYPE_ETHERNET:
647 return EthernetDataTracker.getInstance();
648 default:
649 throw new IllegalArgumentException(
650 "Trying to create a NetworkStateTracker for an unknown radio type: "
651 + config.radio);
652 }
653 }
654 }
655
656 /**
657 * Loads external WiMAX library and registers as system service, returning a
658 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
659 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
660 */
661 private static NetworkStateTracker makeWimaxStateTracker(
662 Context context, Handler trackerHandler) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700663 // Initialize Wimax
tk.mun093f55c2011-10-13 22:51:57 +0900664 DexClassLoader wimaxClassLoader;
665 Class wimaxStateTrackerClass = null;
666 Class wimaxServiceClass = null;
667 Class wimaxManagerClass;
668 String wimaxJarLocation;
669 String wimaxLibLocation;
670 String wimaxManagerClassName;
671 String wimaxServiceClassName;
672 String wimaxStateTrackerClassName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800673
tk.mun093f55c2011-10-13 22:51:57 +0900674 NetworkStateTracker wimaxStateTracker = null;
675
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700676 boolean isWimaxEnabled = context.getResources().getBoolean(
tk.mun093f55c2011-10-13 22:51:57 +0900677 com.android.internal.R.bool.config_wimaxEnabled);
678
679 if (isWimaxEnabled) {
680 try {
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700681 wimaxJarLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900682 com.android.internal.R.string.config_wimaxServiceJarLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700683 wimaxLibLocation = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900684 com.android.internal.R.string.config_wimaxNativeLibLocation);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700685 wimaxManagerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900686 com.android.internal.R.string.config_wimaxManagerClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700687 wimaxServiceClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900688 com.android.internal.R.string.config_wimaxServiceClassname);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700689 wimaxStateTrackerClassName = context.getResources().getString(
tk.mun093f55c2011-10-13 22:51:57 +0900690 com.android.internal.R.string.config_wimaxStateTrackerClassname);
691
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800692 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
tk.mun093f55c2011-10-13 22:51:57 +0900693 wimaxClassLoader = new DexClassLoader(wimaxJarLocation,
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700694 new ContextWrapper(context).getCacheDir().getAbsolutePath(),
tk.mun093f55c2011-10-13 22:51:57 +0900695 wimaxLibLocation, ClassLoader.getSystemClassLoader());
696
697 try {
698 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
699 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
700 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
701 } catch (ClassNotFoundException ex) {
702 loge("Exception finding Wimax classes: " + ex.toString());
703 return null;
704 }
705 } catch(Resources.NotFoundException ex) {
706 loge("Wimax Resources does not exist!!! ");
707 return null;
708 }
709
710 try {
Dianne Hackborndd62fef2012-11-08 11:12:09 -0800711 if (DBG) log("Starting Wimax Service... ");
tk.mun093f55c2011-10-13 22:51:57 +0900712
713 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
714 (new Class[] {Context.class, Handler.class});
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700715 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
716 context, trackerHandler);
tk.mun093f55c2011-10-13 22:51:57 +0900717
718 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
719 (new Class[] {Context.class, wimaxStateTrackerClass});
720 wmxSrvConst.setAccessible(true);
Jeff Sharkey6b9021d2012-07-26 18:32:30 -0700721 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
tk.mun093f55c2011-10-13 22:51:57 +0900722 wmxSrvConst.setAccessible(false);
723
724 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
725
726 } catch(Exception ex) {
727 loge("Exception creating Wimax classes: " + ex.toString());
728 return null;
729 }
730 } else {
731 loge("Wimax is not enabled or not added to the network attributes!!! ");
732 return null;
733 }
734
735 return wimaxStateTracker;
736 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700737
The Android Open Source Project28527d22009-03-03 19:31:44 -0800738 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700739 * Sets the preferred network.
The Android Open Source Project28527d22009-03-03 19:31:44 -0800740 * @param preference the new preference
741 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700742 public void setNetworkPreference(int preference) {
The Android Open Source Project28527d22009-03-03 19:31:44 -0800743 enforceChangePermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700744
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700745 mHandler.sendMessage(
746 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
The Android Open Source Project28527d22009-03-03 19:31:44 -0800747 }
748
749 public int getNetworkPreference() {
750 enforceAccessPermission();
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700751 int preference;
752 synchronized(this) {
753 preference = mNetworkPreference;
754 }
755 return preference;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800756 }
757
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700758 private void handleSetNetworkPreference(int preference) {
759 if (ConnectivityManager.isNetworkTypeValid(preference) &&
Robert Greenwalt34848c02011-03-25 13:09:25 -0700760 mNetConfigs[preference] != null &&
761 mNetConfigs[preference].isDefault()) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700762 if (mNetworkPreference != preference) {
763 final ContentResolver cr = mContext.getContentResolver();
Jeff Brown87272712012-09-25 15:03:20 -0700764 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700765 synchronized(this) {
766 mNetworkPreference = preference;
767 }
768 enforcePreference();
769 }
770 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800771 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700772
Wink Saville4f0de1e2011-08-04 15:01:58 -0700773 private int getConnectivityChangeDelay() {
774 final ContentResolver cr = mContext.getContentResolver();
775
776 /** Check system properties for the default value then use secure settings value, if any. */
777 int defaultDelay = SystemProperties.getInt(
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -0700778 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
779 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
780 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
Wink Saville4f0de1e2011-08-04 15:01:58 -0700781 defaultDelay);
782 }
783
The Android Open Source Project28527d22009-03-03 19:31:44 -0800784 private int getPersistedNetworkPreference() {
785 final ContentResolver cr = mContext.getContentResolver();
786
Jeff Brown87272712012-09-25 15:03:20 -0700787 final int networkPrefSetting = Settings.Global
788 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800789
Jianzheng Zhoua8aa1602012-11-16 13:45:20 +0800790 return networkPrefSetting;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800791 }
Robert Greenwalt0659da32009-07-16 17:21:39 -0700792
The Android Open Source Project28527d22009-03-03 19:31:44 -0800793 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -0700794 * Make the state of network connectivity conform to the preference settings
The Android Open Source Project28527d22009-03-03 19:31:44 -0800795 * In this method, we only tear down a non-preferred network. Establishing
796 * a connection to the preferred network is taken care of when we handle
797 * the disconnect event from the non-preferred network
798 * (see {@link #handleDisconnect(NetworkInfo)}).
799 */
800 private void enforcePreference() {
Robert Greenwalt2034b912009-08-12 16:08:25 -0700801 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
The Android Open Source Project28527d22009-03-03 19:31:44 -0800802 return;
803
Robert Greenwalt2034b912009-08-12 16:08:25 -0700804 if (!mNetTrackers[mNetworkPreference].isAvailable())
805 return;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800806
Robert Greenwalt2034b912009-08-12 16:08:25 -0700807 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -0700808 if (t != mNetworkPreference && mNetTrackers[t] != null &&
Robert Greenwalt2034b912009-08-12 16:08:25 -0700809 mNetTrackers[t].getNetworkInfo().isConnected()) {
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700810 if (DBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -0800811 log("tearing down " + mNetTrackers[t].getNetworkInfo() +
Robert Greenwaltf3f045b2009-08-20 15:25:14 -0700812 " in enforcePreference");
813 }
Robert Greenwalt2034b912009-08-12 16:08:25 -0700814 teardown(mNetTrackers[t]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800815 }
816 }
817 }
818
819 private boolean teardown(NetworkStateTracker netTracker) {
820 if (netTracker.teardown()) {
821 netTracker.setTeardownRequested(true);
822 return true;
823 } else {
824 return false;
825 }
826 }
827
828 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700829 * Check if UID should be blocked from using the network represented by the
830 * given {@link NetworkStateTracker}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700831 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700832 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
833 final String iface = tracker.getLinkProperties().getInterfaceName();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700834
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700835 final boolean networkCostly;
836 final int uidRules;
837 synchronized (mRulesLock) {
838 networkCostly = mMeteredIfaces.contains(iface);
839 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700840 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700841
842 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
843 return true;
844 }
845
846 // no restrictive rules; network is visible
847 return false;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700848 }
849
850 /**
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700851 * Return a filtered {@link NetworkInfo}, potentially marked
852 * {@link DetailedState#BLOCKED} based on
853 * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700854 */
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700855 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
856 NetworkInfo info = tracker.getNetworkInfo();
857 if (isNetworkBlocked(tracker, uid)) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700858 // network is blocked; clone and override state
859 info = new NetworkInfo(info);
860 info.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700861 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700862 if (mLockdownTracker != null) {
863 info = mLockdownTracker.augmentNetworkInfo(info);
864 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700865 return info;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700866 }
867
868 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -0800869 * Return NetworkInfo for the active (i.e., connected) network interface.
870 * It is assumed that at most one network is active at a time. If more
871 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -0700872 * @return the info for the active network, or {@code null} if none is
873 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -0800874 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700875 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800876 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700877 enforceAccessPermission();
878 final int uid = Binder.getCallingUid();
879 return getNetworkInfo(mActiveDefaultNetwork, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800880 }
881
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -0700882 public NetworkInfo getActiveNetworkInfoUnfiltered() {
883 enforceAccessPermission();
884 if (isNetworkTypeValid(mActiveDefaultNetwork)) {
885 final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
886 if (tracker != null) {
887 return tracker.getNetworkInfo();
888 }
889 }
890 return null;
891 }
892
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700893 @Override
894 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
895 enforceConnectivityInternalPermission();
896 return getNetworkInfo(mActiveDefaultNetwork, uid);
897 }
898
899 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800900 public NetworkInfo getNetworkInfo(int networkType) {
901 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700902 final int uid = Binder.getCallingUid();
903 return getNetworkInfo(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800904 }
905
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700906 private NetworkInfo getNetworkInfo(int networkType, int uid) {
907 NetworkInfo info = null;
908 if (isNetworkTypeValid(networkType)) {
909 final NetworkStateTracker tracker = mNetTrackers[networkType];
910 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700911 info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700912 }
913 }
914 return info;
915 }
916
917 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -0800918 public NetworkInfo[] getAllNetworkInfo() {
919 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700920 final int uid = Binder.getCallingUid();
Jeff Sharkey21062e72011-05-28 20:56:34 -0700921 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700922 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700923 for (NetworkStateTracker tracker : mNetTrackers) {
924 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700925 result.add(getFilteredNetworkInfo(tracker, uid));
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700926 }
927 }
The Android Open Source Project28527d22009-03-03 19:31:44 -0800928 }
Jeff Sharkey21062e72011-05-28 20:56:34 -0700929 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800930 }
931
Robert Greenwalt0114f6e2011-08-31 11:46:42 -0700932 @Override
933 public boolean isNetworkSupported(int networkType) {
934 enforceAccessPermission();
935 return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
936 }
937
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700938 /**
939 * Return LinkProperties for the active (i.e., connected) default
940 * network interface. It is assumed that at most one default network
941 * is active at a time. If more than one is active, it is indeterminate
942 * which will be returned.
943 * @return the ip properties for the active network, or {@code null} if
944 * none is active
945 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700946 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700947 public LinkProperties getActiveLinkProperties() {
Robert Greenwalte1544bb2011-05-20 12:23:41 -0700948 return getLinkProperties(mActiveDefaultNetwork);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700949 }
950
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700951 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700952 public LinkProperties getLinkProperties(int networkType) {
953 enforceAccessPermission();
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700954 if (isNetworkTypeValid(networkType)) {
955 final NetworkStateTracker tracker = mNetTrackers[networkType];
956 if (tracker != null) {
957 return tracker.getLinkProperties();
958 }
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -0700959 }
960 return null;
961 }
962
Jeff Sharkey21062e72011-05-28 20:56:34 -0700963 @Override
964 public NetworkState[] getAllNetworkState() {
965 enforceAccessPermission();
966 final int uid = Binder.getCallingUid();
967 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700968 synchronized (mRulesLock) {
Jeff Sharkey21062e72011-05-28 20:56:34 -0700969 for (NetworkStateTracker tracker : mNetTrackers) {
970 if (tracker != null) {
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700971 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
Jeff Sharkey21062e72011-05-28 20:56:34 -0700972 result.add(new NetworkState(
973 info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
974 }
975 }
976 }
977 return result.toArray(new NetworkState[result.size()]);
978 }
979
Jeff Sharkey66fa9682011-08-02 17:22:34 -0700980 private NetworkState getNetworkStateUnchecked(int networkType) {
981 if (isNetworkTypeValid(networkType)) {
982 final NetworkStateTracker tracker = mNetTrackers[networkType];
983 if (tracker != null) {
984 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
985 tracker.getLinkCapabilities());
986 }
987 }
988 return null;
989 }
990
991 @Override
992 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
993 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -0700994
995 final long token = Binder.clearCallingIdentity();
996 try {
997 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
998 if (state != null) {
999 try {
1000 return mPolicyManager.getNetworkQuotaInfo(state);
1001 } catch (RemoteException e) {
1002 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001003 }
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001004 return null;
1005 } finally {
1006 Binder.restoreCallingIdentity(token);
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001007 }
Jeff Sharkey66fa9682011-08-02 17:22:34 -07001008 }
1009
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001010 @Override
1011 public boolean isActiveNetworkMetered() {
1012 enforceAccessPermission();
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001013 final long token = Binder.clearCallingIdentity();
1014 try {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001015 return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
Jeff Sharkey3022ee12012-04-17 12:23:40 -07001016 } finally {
1017 Binder.restoreCallingIdentity(token);
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001018 }
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07001019 }
1020
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001021 private boolean isNetworkMeteredUnchecked(int networkType) {
1022 final NetworkState state = getNetworkStateUnchecked(networkType);
1023 if (state != null) {
1024 try {
1025 return mPolicyManager.isNetworkMetered(state);
1026 } catch (RemoteException e) {
1027 }
1028 }
1029 return false;
1030 }
1031
The Android Open Source Project28527d22009-03-03 19:31:44 -08001032 public boolean setRadios(boolean turnOn) {
1033 boolean result = true;
1034 enforceChangePermission();
1035 for (NetworkStateTracker t : mNetTrackers) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001036 if (t != null) result = t.setRadio(turnOn) && result;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001037 }
1038 return result;
1039 }
1040
1041 public boolean setRadio(int netType, boolean turnOn) {
1042 enforceChangePermission();
1043 if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1044 return false;
1045 }
1046 NetworkStateTracker tracker = mNetTrackers[netType];
1047 return tracker != null && tracker.setRadio(turnOn);
1048 }
1049
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001050 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1051 @Override
Haoyu Baib5da5752012-06-20 14:29:57 -07001052 public void interfaceClassDataActivityChanged(String label, boolean active) {
1053 int deviceType = Integer.parseInt(label);
1054 sendDataActivityBroadcast(deviceType, active);
1055 }
Jeff Sharkey60e6c1a2012-08-05 14:29:23 -07001056 };
Haoyu Baib5da5752012-06-20 14:29:57 -07001057
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001058 /**
1059 * Used to notice when the calling process dies so we can self-expire
1060 *
1061 * Also used to know if the process has cleaned up after itself when
1062 * our auto-expire timer goes off. The timer has a link to an object.
1063 *
1064 */
Robert Greenwalt2034b912009-08-12 16:08:25 -07001065 private class FeatureUser implements IBinder.DeathRecipient {
1066 int mNetworkType;
1067 String mFeature;
1068 IBinder mBinder;
1069 int mPid;
1070 int mUid;
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001071 long mCreateTime;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001072
1073 FeatureUser(int type, String feature, IBinder binder) {
1074 super();
1075 mNetworkType = type;
1076 mFeature = feature;
1077 mBinder = binder;
1078 mPid = getCallingPid();
1079 mUid = getCallingUid();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001080 mCreateTime = System.currentTimeMillis();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001081
Robert Greenwalt2034b912009-08-12 16:08:25 -07001082 try {
1083 mBinder.linkToDeath(this, 0);
1084 } catch (RemoteException e) {
1085 binderDied();
1086 }
1087 }
1088
1089 void unlinkDeathRecipient() {
1090 mBinder.unlinkToDeath(this, 0);
1091 }
1092
1093 public void binderDied() {
Wink Savillee70c6f52010-12-03 12:01:38 -08001094 log("ConnectivityService FeatureUser binderDied(" +
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001095 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1096 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001097 stopUsingNetworkFeature(this, false);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001098 }
1099
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001100 public void expire() {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001101 if (VDBG) {
1102 log("ConnectivityService FeatureUser expire(" +
1103 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1104 (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1105 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001106 stopUsingNetworkFeature(this, false);
1107 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001108
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001109 public boolean isSameUser(FeatureUser u) {
1110 if (u == null) return false;
1111
1112 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1113 }
1114
1115 public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1116 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1117 TextUtils.equals(mFeature, feature)) {
1118 return true;
1119 }
1120 return false;
1121 }
1122
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08001123 public String toString() {
1124 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1125 (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1126 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001127 }
1128
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001129 // javadoc from interface
Robert Greenwalt2034b912009-08-12 16:08:25 -07001130 public int startUsingNetworkFeature(int networkType, String feature,
1131 IBinder binder) {
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001132 long startTime = 0;
1133 if (DBG) {
1134 startTime = SystemClock.elapsedRealtime();
1135 }
Wink Savillea7d56572011-09-21 11:05:43 -07001136 if (VDBG) {
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001137 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1138 + Binder.getCallingUid());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001139 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001140 enforceChangePermission();
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001141 try {
1142 if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1143 mNetConfigs[networkType] == null) {
Wink Saville64e3f782012-07-10 12:37:54 -07001144 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001145 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001146
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001147 FeatureUser f = new FeatureUser(networkType, feature, binder);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001148
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001149 // TODO - move this into individual networktrackers
1150 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001151
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001152 if (mLockdownEnabled) {
1153 // Since carrier APNs usually aren't available from VPN
1154 // endpoint, mark them as unavailable.
1155 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1156 }
1157
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001158 if (mProtectedNetworks.contains(usedNetworkType)) {
1159 enforceConnectivityInternalPermission();
1160 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001161
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001162 // if UID is restricted, don't allow them to bring up metered APNs
1163 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1164 final int uidRules;
1165 synchronized (mRulesLock) {
1166 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1167 }
1168 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
Wink Saville64e3f782012-07-10 12:37:54 -07001169 return PhoneConstants.APN_REQUEST_FAILED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001170 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07001171
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001172 NetworkStateTracker network = mNetTrackers[usedNetworkType];
1173 if (network != null) {
1174 Integer currentPid = new Integer(getCallingPid());
1175 if (usedNetworkType != networkType) {
1176 NetworkInfo ni = network.getNetworkInfo();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001177
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001178 if (ni.isAvailable() == false) {
1179 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1180 if (DBG) log("special network not available ni=" + ni.getTypeName());
Wink Saville64e3f782012-07-10 12:37:54 -07001181 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001182 } else {
1183 // else make the attempt anyway - probably giving REQUEST_STARTED below
1184 if (DBG) {
1185 log("special network not available, but try anyway ni=" +
1186 ni.getTypeName());
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001187 }
1188 }
1189 }
1190
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001191 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001192
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001193 synchronized(this) {
1194 boolean addToList = true;
1195 if (restoreTimer < 0) {
1196 // In case there is no timer is specified for the feature,
1197 // make sure we don't add duplicate entry with the same request.
1198 for (FeatureUser u : mFeatureUsers) {
1199 if (u.isSameUser(f)) {
1200 // Duplicate user is found. Do not add.
1201 addToList = false;
1202 break;
1203 }
1204 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001205 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001206
1207 if (addToList) mFeatureUsers.add(f);
1208 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1209 // this gets used for per-pid dns when connected
1210 mNetRequestersPids[usedNetworkType].add(currentPid);
1211 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001212 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001213
1214 if (restoreTimer >= 0) {
1215 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1216 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1217 }
1218
1219 if ((ni.isConnectedOrConnecting() == true) &&
1220 !network.isTeardownRequested()) {
1221 if (ni.isConnected() == true) {
1222 final long token = Binder.clearCallingIdentity();
1223 try {
1224 // add the pid-specific dns
1225 handleDnsConfigurationChange(usedNetworkType);
1226 if (VDBG) log("special network already active");
1227 } finally {
1228 Binder.restoreCallingIdentity(token);
1229 }
Wink Saville64e3f782012-07-10 12:37:54 -07001230 return PhoneConstants.APN_ALREADY_ACTIVE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001231 }
1232 if (VDBG) log("special network already connecting");
Wink Saville64e3f782012-07-10 12:37:54 -07001233 return PhoneConstants.APN_REQUEST_STARTED;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001234 }
1235
1236 // check if the radio in play can make another contact
1237 // assume if cannot for now
1238
1239 if (DBG) {
1240 log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1241 feature);
1242 }
Mikael Hedegrenb5125b02012-12-14 15:52:52 +01001243 if (network.reconnect()) {
1244 return PhoneConstants.APN_REQUEST_STARTED;
1245 } else {
1246 return PhoneConstants.APN_REQUEST_FAILED;
1247 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001248 } else {
1249 // need to remember this unsupported request so we respond appropriately on stop
1250 synchronized(this) {
1251 mFeatureUsers.add(f);
1252 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1253 // this gets used for per-pid dns when connected
1254 mNetRequestersPids[usedNetworkType].add(currentPid);
1255 }
Robert Greenwalt5364d752010-12-15 13:26:33 -08001256 }
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001257 return -1;
Robert Greenwalt5364d752010-12-15 13:26:33 -08001258 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001259 }
Wink Saville64e3f782012-07-10 12:37:54 -07001260 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
Robert Greenwalt1e6991e2012-05-22 16:07:46 -07001261 } finally {
1262 if (DBG) {
1263 final long execTime = SystemClock.elapsedRealtime() - startTime;
1264 if (execTime > 250) {
1265 loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1266 } else {
1267 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1268 }
1269 }
1270 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001271 }
1272
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001273 // javadoc from interface
The Android Open Source Project28527d22009-03-03 19:31:44 -08001274 public int stopUsingNetworkFeature(int networkType, String feature) {
Robert Greenwalt28f43012009-10-06 17:52:40 -07001275 enforceChangePermission();
1276
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001277 int pid = getCallingPid();
1278 int uid = getCallingUid();
1279
1280 FeatureUser u = null;
1281 boolean found = false;
1282
1283 synchronized(this) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001284 for (FeatureUser x : mFeatureUsers) {
1285 if (x.isSameUser(pid, uid, networkType, feature)) {
1286 u = x;
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001287 found = true;
1288 break;
1289 }
1290 }
1291 }
1292 if (found && u != null) {
1293 // stop regardless of how many other time this proc had called start
1294 return stopUsingNetworkFeature(u, true);
1295 } else {
1296 // none found!
Wink Savillea7d56572011-09-21 11:05:43 -07001297 if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001298 return 1;
1299 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001300 }
1301
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001302 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1303 int networkType = u.mNetworkType;
1304 String feature = u.mFeature;
1305 int pid = u.mPid;
1306 int uid = u.mUid;
1307
1308 NetworkStateTracker tracker = null;
1309 boolean callTeardown = false; // used to carry our decision outside of sync block
1310
Wink Savillea7d56572011-09-21 11:05:43 -07001311 if (VDBG) {
1312 log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001313 }
Robert Greenwalt28f43012009-10-06 17:52:40 -07001314
The Android Open Source Project28527d22009-03-03 19:31:44 -08001315 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001316 if (DBG) {
1317 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1318 ", net is invalid");
1319 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001320 return -1;
1321 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001322
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001323 // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1324 // sync block
1325 synchronized(this) {
1326 // check if this process still has an outstanding start request
1327 if (!mFeatureUsers.contains(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001328 if (VDBG) {
1329 log("stopUsingNetworkFeature: this process has no outstanding requests" +
1330 ", ignoring");
1331 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001332 return 1;
1333 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001334 u.unlinkDeathRecipient();
1335 mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1336 // If we care about duplicate requests, check for that here.
1337 //
1338 // This is done to support the extension of a request - the app
1339 // can request we start the network feature again and renew the
1340 // auto-shutoff delay. Normal "stop" calls from the app though
1341 // do not pay attention to duplicate requests - in effect the
1342 // API does not refcount and a single stop will counter multiple starts.
1343 if (ignoreDups == false) {
Kazuhiro Ondocae18f12011-07-19 11:23:37 -05001344 for (FeatureUser x : mFeatureUsers) {
1345 if (x.isSameUser(u)) {
Wink Savillea7d56572011-09-21 11:05:43 -07001346 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001347 return 1;
1348 }
1349 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001350 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001351
repo syncf5de5572011-07-29 23:55:49 -07001352 // TODO - move to individual network trackers
1353 int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1354
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001355 tracker = mNetTrackers[usedNetworkType];
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001356 if (tracker == null) {
Wink Savillea7d56572011-09-21 11:05:43 -07001357 if (DBG) {
1358 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1359 " no known tracker for used net type " + usedNetworkType);
1360 }
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001361 return -1;
1362 }
1363 if (usedNetworkType != networkType) {
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001364 Integer currentPid = new Integer(pid);
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001365 mNetRequestersPids[usedNetworkType].remove(currentPid);
Robert Greenwalt17900092013-02-12 17:18:25 -08001366
1367 final long token = Binder.clearCallingIdentity();
1368 try {
1369 reassessPidDns(pid, true);
1370 } finally {
1371 Binder.restoreCallingIdentity(token);
1372 }
Mattias Falkdc919012011-08-23 14:15:13 +02001373 flushVmDnsCache();
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001374 if (mNetRequestersPids[usedNetworkType].size() != 0) {
Wink Savillea7d56572011-09-21 11:05:43 -07001375 if (VDBG) {
1376 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1377 " others still using it");
1378 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001379 return 1;
1380 }
1381 callTeardown = true;
Robert Greenwalt9f3be4c2011-01-10 11:58:31 -08001382 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07001383 if (DBG) {
1384 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1385 " not a known feature - dropping");
1386 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001387 }
1388 }
Wink Savillea7d56572011-09-21 11:05:43 -07001389
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001390 if (callTeardown) {
Wink Savillea7d56572011-09-21 11:05:43 -07001391 if (DBG) {
1392 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1393 }
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07001394 tracker.teardown();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001395 return 1;
1396 } else {
Robert Greenwaltd391e892010-05-18 10:52:51 -07001397 return -1;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001398 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001399 }
1400
1401 /**
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001402 * @deprecated use requestRouteToHostAddress instead
1403 *
The Android Open Source Project28527d22009-03-03 19:31:44 -08001404 * Ensure that a network route exists to deliver traffic to the specified
1405 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001406 * @param networkType the type of the network over which traffic to the
1407 * specified host is to be routed
1408 * @param hostAddress the IP address of the host to which the route is
1409 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08001410 * @return {@code true} on success, {@code false} on failure
1411 */
1412 public boolean requestRouteToHost(int networkType, int hostAddress) {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001413 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1414
1415 if (inetAddress == null) {
1416 return false;
1417 }
1418
1419 return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1420 }
1421
1422 /**
1423 * Ensure that a network route exists to deliver traffic to the specified
1424 * host via the specified network interface.
1425 * @param networkType the type of the network over which traffic to the
1426 * specified host is to be routed
1427 * @param hostAddress the IP address of the host to which the route is
1428 * desired
1429 * @return {@code true} on success, {@code false} on failure
1430 */
1431 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08001432 enforceChangePermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001433 if (mProtectedNetworks.contains(networkType)) {
1434 enforceConnectivityInternalPermission();
1435 }
1436
The Android Open Source Project28527d22009-03-03 19:31:44 -08001437 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001438 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001439 return false;
1440 }
1441 NetworkStateTracker tracker = mNetTrackers[networkType];
Ken Mixter7caa36a2013-11-07 22:08:24 -08001442 DetailedState netState = DetailedState.DISCONNECTED;
1443 if (tracker != null) {
1444 netState = tracker.getNetworkInfo().getDetailedState();
1445 }
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001446
Ken Mixter7caa36a2013-11-07 22:08:24 -08001447 if ((netState != DetailedState.CONNECTED &&
Irfan Sheriffba8388b2012-08-16 12:49:23 -07001448 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001449 tracker.isTeardownRequested()) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001450 if (VDBG) {
Wink Saville690cb182013-06-29 21:10:57 -07001451 log("requestRouteToHostAddress on down network "
1452 + "(" + networkType + ") - dropped"
1453 + " tracker=" + tracker
1454 + " netState=" + netState
1455 + " isTeardownRequested="
1456 + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
Robert Greenwalt4666ed02009-09-10 15:06:20 -07001457 }
1458 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001459 }
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001460 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001461 try {
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -07001462 InetAddress addr = InetAddress.getByAddress(hostAddress);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001463 LinkProperties lp = tracker.getLinkProperties();
Wink Saville690cb182013-06-29 21:10:57 -07001464 boolean ok = addRouteToAddress(lp, addr);
1465 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1466 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001467 } catch (UnknownHostException e) {
1468 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1469 } finally {
1470 Binder.restoreCallingIdentity(token);
1471 }
Wink Saville690cb182013-06-29 21:10:57 -07001472 if (DBG) log("requestRouteToHostAddress X bottom return false");
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07001473 return false;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07001474 }
1475
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001476 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001477 return modifyRoute(p, r, 0, ADD, toDefaultTable);
Robert Greenwaltbd492212011-05-06 17:10:53 -07001478 }
1479
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001480 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001481 return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001482 }
1483
Robert Greenwalt98107422011-07-22 11:55:33 -07001484 private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001485 return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001486 }
1487
1488 private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001489 return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
Robert Greenwalt98107422011-07-22 11:55:33 -07001490 }
1491
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001492 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1493 boolean toDefaultTable) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001494 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07001495 if (bestRoute == null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001496 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07001497 } else {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001498 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07001499 if (bestRoute.getGateway().equals(addr)) {
1500 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001501 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001502 } else {
1503 // if we will connect to this through another route, add a direct route
1504 // to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001505 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07001506 }
1507 }
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001508 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
Robert Greenwalt98107422011-07-22 11:55:33 -07001509 }
1510
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001511 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1512 boolean toDefaultTable) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001513 if ((lp == null) || (r == null)) {
1514 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001515 return false;
1516 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001517
1518 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001519 loge("Error modifying route - too much recursion");
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001520 return false;
1521 }
1522
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001523 String ifaceName = r.getInterface();
1524 if(ifaceName == null) {
1525 loge("Error modifying route - no interface name");
1526 return false;
1527 }
Robert Greenwalt24bc5342013-04-11 13:48:16 -07001528 if (r.hasGateway()) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09001529 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001530 if (bestRoute != null) {
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001531 if (bestRoute.getGateway().equals(r.getGateway())) {
1532 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001533 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
Robert Greenwalt57c83bb2011-07-15 09:45:08 -07001534 } else {
1535 // if we will connect to our gateway through another route, add a direct
1536 // route to it's gateway
Lorenzo Colitti697e1c02013-03-08 12:30:44 -08001537 bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1538 bestRoute.getGateway(),
1539 ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001540 }
Lorenzo Colittif7020e22013-03-12 07:39:59 +09001541 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001542 }
1543 }
1544 if (doAdd) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001545 if (VDBG) log("Adding " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001546 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001547 if (toDefaultTable) {
1548 mAddedRoutes.add(r); // only track default table - only one apps can effect
1549 mNetd.addRoute(ifaceName, r);
1550 } else {
1551 mNetd.addSecondaryRoute(ifaceName, r);
1552 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001553 } catch (Exception e) {
1554 // never crash - catch them all
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08001555 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001556 return false;
1557 }
1558 } else {
1559 // if we remove this one and there are no more like it, then refcount==0 and
1560 // we can remove it from the table
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001561 if (toDefaultTable) {
1562 mAddedRoutes.remove(r);
1563 if (mAddedRoutes.contains(r) == false) {
1564 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1565 try {
1566 mNetd.removeRoute(ifaceName, r);
1567 } catch (Exception e) {
1568 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001569 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001570 return false;
1571 }
1572 } else {
1573 if (VDBG) log("not removing " + r + " as it's still in use");
1574 }
1575 } else {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001576 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001577 try {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07001578 mNetd.removeSecondaryRoute(ifaceName, r);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001579 } catch (Exception e) {
1580 // never crash - catch them all
Robert Greenwalt436db352012-04-23 18:00:37 -07001581 if (VDBG) loge("Exception trying to remove a route: " + e);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001582 return false;
1583 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07001584 }
1585 }
1586 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001587 }
1588
1589 /**
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001590 * @see ConnectivityManager#getMobileDataEnabled()
1591 */
1592 public boolean getMobileDataEnabled() {
Wink Savilleb9024c62010-12-07 10:31:02 -08001593 // TODO: This detail should probably be in DataConnectionTracker's
1594 // which is where we store the value and maybe make this
1595 // asynchronous.
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001596 enforceAccessPermission();
Jeff Sharkey9ee49b32012-09-26 15:54:06 -07001597 boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1598 Settings.Global.MOBILE_DATA, 1) == 1;
Robert Greenwalt78f28112011-08-02 17:18:41 -07001599 if (VDBG) log("getMobileDataEnabled returning " + retVal);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001600 return retVal;
1601 }
1602
Robert Greenwalt34848c02011-03-25 13:09:25 -07001603 public void setDataDependency(int networkType, boolean met) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001604 enforceConnectivityInternalPermission();
1605
Robert Greenwalt34848c02011-03-25 13:09:25 -07001606 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1607 (met ? ENABLED : DISABLED), networkType));
1608 }
1609
1610 private void handleSetDependencyMet(int networkType, boolean met) {
1611 if (mNetTrackers[networkType] != null) {
1612 if (DBG) {
1613 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1614 }
1615 mNetTrackers[networkType].setDependencyMet(met);
1616 }
1617 }
1618
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001619 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1620 @Override
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001621 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001622 // caller is NPMS, since we only register with them
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001623 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001624 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001625 }
1626
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001627 synchronized (mRulesLock) {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001628 // skip update when we've already applied rules
1629 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1630 if (oldRules == uidRules) return;
1631
1632 mUidRules.put(uid, uidRules);
1633 }
1634
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001635 // TODO: notify UID when it has requested targeted updates
1636 }
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001637
1638 @Override
1639 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001640 // caller is NPMS, since we only register with them
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001641 if (LOGD_RULES) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001642 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeya47d7a12011-06-16 15:07:48 -07001643 }
1644
1645 synchronized (mRulesLock) {
1646 mMeteredIfaces.clear();
1647 for (String iface : meteredIfaces) {
1648 mMeteredIfaces.add(iface);
1649 }
1650 }
1651 }
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08001652
1653 @Override
1654 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1655 // caller is NPMS, since we only register with them
1656 if (LOGD_RULES) {
1657 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1658 }
1659
1660 // kick off connectivity change broadcast for active network, since
1661 // global background policy change is radical.
1662 final int networkType = mActiveDefaultNetwork;
1663 if (isNetworkTypeValid(networkType)) {
1664 final NetworkStateTracker tracker = mNetTrackers[networkType];
1665 if (tracker != null) {
1666 final NetworkInfo info = tracker.getNetworkInfo();
1667 if (info != null && info.isConnected()) {
1668 sendConnectedBroadcast(info);
1669 }
1670 }
1671 }
1672 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001673 };
1674
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001675 /**
1676 * @see ConnectivityManager#setMobileDataEnabled(boolean)
1677 */
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001678 public void setMobileDataEnabled(boolean enabled) {
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001679 enforceChangePermission();
Wink Savillee70c6f52010-12-03 12:01:38 -08001680 if (DBG) log("setMobileDataEnabled(" + enabled + ")");
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001681
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001682 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
Robert Greenwalt34848c02011-03-25 13:09:25 -07001683 (enabled ? ENABLED : DISABLED), 0));
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07001684 }
1685
1686 private void handleSetMobileData(boolean enabled) {
Wink Savilleb9024c62010-12-07 10:31:02 -08001687 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07001688 if (VDBG) {
1689 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001690 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001691 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1692 }
tk.mun5eee1042012-01-06 10:43:52 +09001693 if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1694 if (VDBG) {
1695 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1696 }
1697 mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1698 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07001699 }
1700
1701 @Override
1702 public void setPolicyDataEnable(int networkType, boolean enabled) {
1703 // only someone like NPMS should only be calling us
1704 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1705
1706 mHandler.sendMessage(mHandler.obtainMessage(
1707 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1708 }
1709
1710 private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1711 if (isNetworkTypeValid(networkType)) {
1712 final NetworkStateTracker tracker = mNetTrackers[networkType];
1713 if (tracker != null) {
1714 tracker.setPolicyDataEnable(enabled);
1715 }
Robert Greenwalt1b21f6c2010-02-23 18:58:05 -08001716 }
1717 }
1718
The Android Open Source Project28527d22009-03-03 19:31:44 -08001719 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001720 mContext.enforceCallingOrSelfPermission(
1721 android.Manifest.permission.ACCESS_NETWORK_STATE,
1722 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001723 }
1724
1725 private void enforceChangePermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001726 mContext.enforceCallingOrSelfPermission(
1727 android.Manifest.permission.CHANGE_NETWORK_STATE,
1728 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08001729 }
1730
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08001731 // TODO Make this a special check when it goes public
1732 private void enforceTetherChangePermission() {
1733 mContext.enforceCallingOrSelfPermission(
1734 android.Manifest.permission.CHANGE_NETWORK_STATE,
1735 "ConnectivityService");
1736 }
1737
Robert Greenwalt8e87f122010-02-11 18:18:40 -08001738 private void enforceTetherAccessPermission() {
1739 mContext.enforceCallingOrSelfPermission(
1740 android.Manifest.permission.ACCESS_NETWORK_STATE,
1741 "ConnectivityService");
1742 }
1743
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001744 private void enforceConnectivityInternalPermission() {
1745 mContext.enforceCallingOrSelfPermission(
1746 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1747 "ConnectivityService");
1748 }
1749
The Android Open Source Project28527d22009-03-03 19:31:44 -08001750 /**
Robert Greenwalt0659da32009-07-16 17:21:39 -07001751 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1752 * network, we ignore it. If it is for the active network, we send out a
1753 * broadcast. But first, we check whether it might be possible to connect
1754 * to a different network.
The Android Open Source Project28527d22009-03-03 19:31:44 -08001755 * @param info the {@code NetworkInfo} for the network
1756 */
1757 private void handleDisconnect(NetworkInfo info) {
1758
Robert Greenwalt2034b912009-08-12 16:08:25 -07001759 int prevNetType = info.getType();
The Android Open Source Project28527d22009-03-03 19:31:44 -08001760
Robert Greenwalt2034b912009-08-12 16:08:25 -07001761 mNetTrackers[prevNetType].setTeardownRequested(false);
Haoyu Bai92e03a72012-06-28 15:26:19 -07001762
1763 // Remove idletimer previously setup in {@code handleConnect}
1764 removeDataActivityTracking(prevNetType);
1765
The Android Open Source Project28527d22009-03-03 19:31:44 -08001766 /*
1767 * If the disconnected network is not the active one, then don't report
1768 * this as a loss of connectivity. What probably happened is that we're
1769 * getting the disconnect for a network that we explicitly disabled
1770 * in accordance with network preference policies.
1771 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001772 if (!mNetConfigs[prevNetType].isDefault()) {
Mattias Falkdc919012011-08-23 14:15:13 +02001773 List<Integer> pids = mNetRequestersPids[prevNetType];
1774 for (Integer pid : pids) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001775 // will remove them because the net's no longer connected
1776 // need to do this now as only now do we know the pids and
1777 // can properly null things that are no longer referenced.
1778 reassessPidDns(pid.intValue(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001779 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001780 }
1781
The Android Open Source Project28527d22009-03-03 19:31:44 -08001782 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07001783 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001784 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001785 if (info.isFailover()) {
1786 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1787 info.setFailover(false);
1788 }
1789 if (info.getReason() != null) {
1790 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1791 }
1792 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001793 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1794 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001795 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07001796
Robert Greenwalt34848c02011-03-25 13:09:25 -07001797 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001798 tryFailover(prevNetType);
1799 if (mActiveDefaultNetwork != -1) {
1800 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001801 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1802 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001803 mDefaultInetConditionPublished = 0; // we're not connected anymore
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001804 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1805 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001806 }
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001807 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001808
1809 // Reset interface if no other connections are using the same interface
1810 boolean doReset = true;
1811 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1812 if (linkProperties != null) {
1813 String oldIface = linkProperties.getInterfaceName();
1814 if (TextUtils.isEmpty(oldIface) == false) {
1815 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1816 if (networkStateTracker == null) continue;
1817 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1818 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1819 LinkProperties l = networkStateTracker.getLinkProperties();
1820 if (l == null) continue;
1821 if (oldIface.equals(l.getInterfaceName())) {
1822 doReset = false;
1823 break;
1824 }
1825 }
1826 }
1827 }
1828 }
1829
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001830 // do this before we broadcast the change
Robert Greenwalt36ea8692011-06-15 12:22:07 -07001831 handleConnectivityChange(prevNetType, doReset);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001832
Jeff Sharkey971cd162011-08-29 16:02:57 -07001833 final Intent immediateIntent = new Intent(intent);
1834 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1835 sendStickyBroadcast(immediateIntent);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001836 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001837 /*
1838 * If the failover network is already connected, then immediately send
1839 * out a followup broadcast indicating successful failover
1840 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001841 if (mActiveDefaultNetwork != -1) {
Wink Saville4f0de1e2011-08-04 15:01:58 -07001842 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1843 getConnectivityChangeDelay());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001844 }
1845 }
1846
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001847 private void tryFailover(int prevNetType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001848 /*
Robert Greenwalt92564852011-01-06 15:41:07 -08001849 * If this is a default network, check if other defaults are available.
1850 * Try to reconnect on all available and let them hash it out when
1851 * more than one connects.
Robert Greenwalt2034b912009-08-12 16:08:25 -07001852 */
Robert Greenwalt34848c02011-03-25 13:09:25 -07001853 if (mNetConfigs[prevNetType].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07001854 if (mActiveDefaultNetwork == prevNetType) {
1855 mActiveDefaultNetwork = -1;
1856 }
1857
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001858 // don't signal a reconnect for anything lower or equal priority than our
1859 // current connected default
1860 // TODO - don't filter by priority now - nice optimization but risky
1861// int currentPriority = -1;
1862// if (mActiveDefaultNetwork != -1) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07001863// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001864// }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001865 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
Robert Greenwaltec05b3c2009-10-30 14:17:42 -07001866 if (checkType == prevNetType) continue;
Robert Greenwalt34848c02011-03-25 13:09:25 -07001867 if (mNetConfigs[checkType] == null) continue;
1868 if (!mNetConfigs[checkType].isDefault()) continue;
Robert Greenwaltbc026d02011-11-11 09:56:03 -08001869 if (mNetTrackers[checkType] == null) continue;
Wink Saville72a95b92011-01-26 15:43:49 -08001870
1871// Enabling the isAvailable() optimization caused mobile to not get
1872// selected if it was in the middle of error handling. Specifically
1873// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1874// would not be available and we wouldn't get connected to anything.
1875// So removing the isAvailable() optimization below for now. TODO: This
1876// optimization should work and we need to investigate why it doesn't work.
1877// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1878// complete before it is really complete.
1879// if (!mNetTrackers[checkType].isAvailable()) continue;
1880
Robert Greenwalt34848c02011-03-25 13:09:25 -07001881// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001882
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001883 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1884 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1885 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1886 checkInfo.setFailover(true);
1887 checkTracker.reconnect();
Robert Greenwalt2034b912009-08-12 16:08:25 -07001888 }
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001889 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001890 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001891 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001892 }
1893
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001894 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08001895 enforceConnectivityInternalPermission();
Jeff Sharkey971cd162011-08-29 16:02:57 -07001896 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1897 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001898 }
1899
Wink Saville4f0de1e2011-08-04 15:01:58 -07001900 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07001901 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1902 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001903 }
1904
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001905 private void sendInetConditionBroadcast(NetworkInfo info) {
1906 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1907 }
1908
Wink Saville4f0de1e2011-08-04 15:01:58 -07001909 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07001910 if (mLockdownTracker != null) {
1911 info = mLockdownTracker.augmentNetworkInfo(info);
1912 }
1913
Robert Greenwaltd3401f92010-09-15 17:36:33 -07001914 Intent intent = new Intent(bcastType);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07001915 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001916 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001917 if (info.isFailover()) {
1918 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1919 info.setFailover(false);
1920 }
1921 if (info.getReason() != null) {
1922 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1923 }
1924 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07001925 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1926 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08001927 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07001928 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07001929 return intent;
1930 }
1931
1932 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1933 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1934 }
1935
1936 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1937 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001938 }
1939
Haoyu Baib5da5752012-06-20 14:29:57 -07001940 private void sendDataActivityBroadcast(int deviceType, boolean active) {
1941 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1942 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1943 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07001944 final long ident = Binder.clearCallingIdentity();
1945 try {
1946 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1947 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1948 } finally {
1949 Binder.restoreCallingIdentity(ident);
1950 }
Haoyu Baib5da5752012-06-20 14:29:57 -07001951 }
1952
The Android Open Source Project28527d22009-03-03 19:31:44 -08001953 /**
1954 * Called when an attempt to fail over to another network has failed.
1955 * @param info the {@link NetworkInfo} for the failed network
1956 */
1957 private void handleConnectionFailure(NetworkInfo info) {
1958 mNetTrackers[info.getType()].setTeardownRequested(false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001959
Robert Greenwalt2034b912009-08-12 16:08:25 -07001960 String reason = info.getReason();
1961 String extraInfo = info.getExtraInfo();
Robert Greenwalt0659da32009-07-16 17:21:39 -07001962
Robert Greenwalte981bc52010-10-08 16:35:52 -07001963 String reasonText;
1964 if (reason == null) {
1965 reasonText = ".";
1966 } else {
1967 reasonText = " (" + reason + ").";
The Android Open Source Project28527d22009-03-03 19:31:44 -08001968 }
Wink Savillee70c6f52010-12-03 12:01:38 -08001969 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Robert Greenwalt2034b912009-08-12 16:08:25 -07001970
1971 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
Irfan Sheriff2e617a72012-09-20 09:32:41 -07001972 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07001973 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
Robert Greenwalt2034b912009-08-12 16:08:25 -07001974 if (getActiveNetworkInfo() == null) {
1975 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1976 }
1977 if (reason != null) {
1978 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1979 }
1980 if (extraInfo != null) {
1981 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1982 }
1983 if (info.isFailover()) {
1984 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1985 info.setFailover(false);
1986 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001987
Robert Greenwalt34848c02011-03-25 13:09:25 -07001988 if (mNetConfigs[info.getType()].isDefault()) {
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08001989 tryFailover(info.getType());
1990 if (mActiveDefaultNetwork != -1) {
1991 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001992 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1993 } else {
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001994 mDefaultInetConditionPublished = 0;
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001995 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1996 }
Robert Greenwaltf55ced92010-01-20 19:29:41 -08001997 }
Robert Greenwalt3cc68d32010-01-25 17:54:29 -08001998
Robert Greenwaltb2a9e492010-09-20 18:01:43 -07001999 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Jeff Sharkey971cd162011-08-29 16:02:57 -07002000
2001 final Intent immediateIntent = new Intent(intent);
2002 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2003 sendStickyBroadcast(immediateIntent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002004 sendStickyBroadcast(intent);
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002005 /*
2006 * If the failover network is already connected, then immediately send
2007 * out a followup broadcast indicating successful failover
2008 */
Robert Greenwalt4b7c55e2011-01-11 13:56:33 -08002009 if (mActiveDefaultNetwork != -1) {
2010 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
Robert Greenwaltf55ced92010-01-20 19:29:41 -08002011 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002012 }
2013
2014 private void sendStickyBroadcast(Intent intent) {
2015 synchronized(this) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002016 if (!mSystemReady) {
2017 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002018 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002019 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Wink Savillea7d56572011-09-21 11:05:43 -07002020 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002021 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002022 }
2023
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002024 final long ident = Binder.clearCallingIdentity();
2025 try {
2026 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2027 } finally {
2028 Binder.restoreCallingIdentity(ident);
2029 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002030 }
2031 }
2032
Wink Saville4f0de1e2011-08-04 15:01:58 -07002033 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2034 if (delayMs <= 0) {
2035 sendStickyBroadcast(intent);
2036 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07002037 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002038 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2039 + intent.getAction());
2040 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002041 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2042 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2043 }
2044 }
2045
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002046 void systemReady() {
2047 synchronized(this) {
2048 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002049 if (mInitialBroadcast != null) {
Dianne Hackbornbc55bd12012-08-29 18:32:08 -07002050 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002051 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002052 }
2053 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002054 // load the global proxy at startup
2055 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002056
2057 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2058 // for user to unlock device.
2059 if (!updateLockdownVpn()) {
2060 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2061 mContext.registerReceiver(mUserPresentReceiver, filter);
2062 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002063 }
2064
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002065 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2066 @Override
2067 public void onReceive(Context context, Intent intent) {
2068 // Try creating lockdown tracker, since user present usually means
2069 // unlocked keystore.
2070 if (updateLockdownVpn()) {
2071 mContext.unregisterReceiver(this);
2072 }
2073 }
2074 };
2075
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002076 private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2077 if ((type != mNetworkPreference &&
2078 mNetConfigs[mActiveDefaultNetwork].priority >
2079 mNetConfigs[type].priority) ||
2080 mNetworkPreference == mActiveDefaultNetwork) return false;
2081 return true;
2082 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002083
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002084 private void handleConnect(NetworkInfo info) {
2085 final int newNetType = info.getType();
2086
2087 setupDataActivityTracking(newNetType);
Haoyu Bai92e03a72012-06-28 15:26:19 -07002088
The Android Open Source Project28527d22009-03-03 19:31:44 -08002089 // snapshot isFailover, because sendConnectedBroadcast() resets it
2090 boolean isFailover = info.isFailover();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002091 final NetworkStateTracker thisNet = mNetTrackers[newNetType];
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002092 final String thisIface = thisNet.getLinkProperties().getInterfaceName();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002093
Robert Greenwalt2034b912009-08-12 16:08:25 -07002094 // if this is a default net and other default is running
2095 // kill the one not preferred
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002096 if (mNetConfigs[newNetType].isDefault()) {
2097 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2098 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002099 // tear down the other
2100 NetworkStateTracker otherNet =
2101 mNetTrackers[mActiveDefaultNetwork];
Wink Savillee70c6f52010-12-03 12:01:38 -08002102 if (DBG) {
2103 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
Robert Greenwalt2034b912009-08-12 16:08:25 -07002104 " teardown");
Wink Savillee70c6f52010-12-03 12:01:38 -08002105 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002106 if (!teardown(otherNet)) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002107 loge("Network declined teardown request");
Robert Greenwalt99910172011-03-29 11:36:28 -07002108 teardown(thisNet);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002109 return;
2110 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002111 } else {
2112 // don't accept this one
2113 if (VDBG) {
2114 log("Not broadcasting CONNECT_ACTION " +
2115 "to torn down network " + info.getTypeName());
2116 }
2117 teardown(thisNet);
2118 return;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002119 }
2120 }
2121 synchronized (ConnectivityService.this) {
2122 // have a new default network, release the transition wakelock in a second
2123 // if it's held. The second pause is to allow apps to reconnect over the
2124 // new network
2125 if (mNetTransitionWakeLock.isHeld()) {
2126 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002127 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002128 mNetTransitionWakeLockSerialNumber, 0),
2129 1000);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002130 }
2131 }
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002132 mActiveDefaultNetwork = newNetType;
Robert Greenwalt986c7412010-09-08 15:24:47 -07002133 // this will cause us to come up initially as unconnected and switching
2134 // to connected after our normal pause unless somebody reports us as reall
2135 // disconnected
2136 mDefaultInetConditionPublished = 0;
2137 mDefaultConnectionSequence++;
2138 mInetConditionChangeInFlight = false;
2139 // Don't do this - if we never sign in stay, grey
2140 //reportNetworkCondition(mActiveDefaultNetwork, 100);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002141 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002142 thisNet.setTeardownRequested(false);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002143 updateNetworkSettings(thisNet);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002144 handleConnectivityChange(newNetType, false);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002145 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002146
2147 // notify battery stats service about this network
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07002148 if (thisIface != null) {
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002149 try {
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002150 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
Jeff Sharkeyaac2c502011-10-04 16:54:49 -07002151 } catch (RemoteException e) {
2152 // ignored; service lives in system_server
2153 }
2154 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002155 }
2156
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002157 private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2158 if (DBG) log("Captive portal check " + info);
2159 int type = info.getType();
2160 final NetworkStateTracker thisNet = mNetTrackers[type];
2161 if (mNetConfigs[type].isDefault()) {
2162 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2163 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2164 if (DBG) log("Captive check on " + info.getTypeName());
Irfan Sheriff2e617a72012-09-20 09:32:41 -07002165 mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002166 return;
2167 } else {
2168 if (DBG) log("Tear down low priority net " + info.getTypeName());
2169 teardown(thisNet);
2170 return;
2171 }
2172 }
2173 }
2174
2175 thisNet.captivePortalCheckComplete();
2176 }
2177
2178 /** @hide */
2179 public void captivePortalCheckComplete(NetworkInfo info) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002180 enforceConnectivityInternalPermission();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002181 mNetTrackers[info.getType()].captivePortalCheckComplete();
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002182 }
2183
The Android Open Source Project28527d22009-03-03 19:31:44 -08002184 /**
Haoyu Bai92e03a72012-06-28 15:26:19 -07002185 * Setup data activity tracking for the given network interface.
2186 *
2187 * Every {@code setupDataActivityTracking} should be paired with a
2188 * {@link removeDataActivityTracking} for cleanup.
2189 */
2190 private void setupDataActivityTracking(int type) {
2191 final NetworkStateTracker thisNet = mNetTrackers[type];
2192 final String iface = thisNet.getLinkProperties().getInterfaceName();
2193
2194 final int timeout;
2195
2196 if (ConnectivityManager.isNetworkTypeMobile(type)) {
Jeff Brown87272712012-09-25 15:03:20 -07002197 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2198 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002199 0);
2200 // Canonicalize mobile network type
2201 type = ConnectivityManager.TYPE_MOBILE;
2202 } else if (ConnectivityManager.TYPE_WIFI == type) {
Jeff Brown87272712012-09-25 15:03:20 -07002203 timeout = Settings.Global.getInt(mContext.getContentResolver(),
2204 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai92e03a72012-06-28 15:26:19 -07002205 0);
2206 } else {
2207 // do not track any other networks
2208 timeout = 0;
2209 }
2210
2211 if (timeout > 0 && iface != null) {
2212 try {
2213 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2214 } catch (RemoteException e) {
2215 }
2216 }
2217 }
2218
2219 /**
2220 * Remove data activity tracking when network disconnects.
2221 */
2222 private void removeDataActivityTracking(int type) {
2223 final NetworkStateTracker net = mNetTrackers[type];
2224 final String iface = net.getLinkProperties().getInterfaceName();
2225
2226 if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2227 ConnectivityManager.TYPE_WIFI == type)) {
2228 try {
2229 // the call fails silently if no idletimer setup for this interface
2230 mNetd.removeIdleTimer(iface);
2231 } catch (RemoteException e) {
2232 }
2233 }
2234 }
2235
2236 /**
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002237 * After a change in the connectivity state of a network. We're mainly
2238 * concerned with making sure that the list of DNS servers is set up
2239 * according to which networks are connected, and ensuring that the
2240 * right routing table entries exist.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002241 */
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002242 private void handleConnectivityChange(int netType, boolean doReset) {
Wink Saville051a6642011-07-13 13:44:13 -07002243 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2244
The Android Open Source Project28527d22009-03-03 19:31:44 -08002245 /*
Robert Greenwalt2034b912009-08-12 16:08:25 -07002246 * If a non-default network is enabled, add the host routes that
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002247 * will allow it's DNS servers to be accessed.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002248 */
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002249 handleDnsConfigurationChange(netType);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002250
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002251 LinkProperties curLp = mCurrentLinkProperties[netType];
2252 LinkProperties newLp = null;
2253
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002254 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002255 newLp = mNetTrackers[netType].getLinkProperties();
Wink Saville051a6642011-07-13 13:44:13 -07002256 if (VDBG) {
2257 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2258 " doReset=" + doReset + " resetMask=" + resetMask +
2259 "\n curLp=" + curLp +
2260 "\n newLp=" + newLp);
2261 }
2262
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002263 if (curLp != null) {
2264 if (curLp.isIdenticalInterfaceName(newLp)) {
2265 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2266 if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2267 for (LinkAddress linkAddr : car.removed) {
2268 if (linkAddr.getAddress() instanceof Inet4Address) {
2269 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2270 }
2271 if (linkAddr.getAddress() instanceof Inet6Address) {
2272 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2273 }
Wink Saville051a6642011-07-13 13:44:13 -07002274 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002275 if (DBG) {
2276 log("handleConnectivityChange: addresses changed" +
2277 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2278 "\n car=" + car);
Wink Saville051a6642011-07-13 13:44:13 -07002279 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002280 } else {
2281 if (DBG) {
2282 log("handleConnectivityChange: address are the same reset per doReset" +
2283 " linkProperty[" + netType + "]:" +
2284 " resetMask=" + resetMask);
2285 }
Wink Saville051a6642011-07-13 13:44:13 -07002286 }
2287 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002288 resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
Robert Greenwalt78f28112011-08-02 17:18:41 -07002289 if (DBG) {
2290 log("handleConnectivityChange: interface not not equivalent reset both" +
2291 " linkProperty[" + netType + "]:" +
2292 " resetMask=" + resetMask);
2293 }
Wink Saville051a6642011-07-13 13:44:13 -07002294 }
Wink Saville051a6642011-07-13 13:44:13 -07002295 }
Robert Greenwalt34848c02011-03-25 13:09:25 -07002296 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07002297 handleApplyDefaultProxy(newLp.getHttpProxy());
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002298 }
2299 } else {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002300 if (VDBG) {
2301 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2302 " doReset=" + doReset + " resetMask=" + resetMask +
2303 "\n curLp=" + curLp +
2304 "\n newLp= null");
Robert Greenwalt2034b912009-08-12 16:08:25 -07002305 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002306 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002307 mCurrentLinkProperties[netType] = newLp;
Robert Greenwalt8d777252011-08-15 12:31:55 -07002308 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002309
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002310 if (resetMask != 0 || resetDns) {
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002311 if (curLp != null) {
2312 for (String iface : curLp.getAllInterfaceNames()) {
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002313 if (TextUtils.isEmpty(iface) == false) {
2314 if (resetMask != 0) {
2315 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2316 NetworkUtils.resetConnections(iface, resetMask);
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002317
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002318 // Tell VPN the interface is down. It is a temporary
2319 // but effective fix to make VPN aware of the change.
2320 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2321 mVpn.interfaceStatusChanged(iface, false);
2322 }
Chia-chi Yeh4a243f52011-08-15 15:19:40 -07002323 }
Lorenzo Colittia546d7e2013-03-20 19:22:58 +09002324 if (resetDns) {
2325 flushVmDnsCache();
2326 if (VDBG) log("resetting DNS cache for " + iface);
2327 try {
2328 mNetd.flushInterfaceDnsCache(iface);
2329 } catch (Exception e) {
2330 // never crash - catch them all
2331 if (DBG) loge("Exception resetting dns cache: " + e);
2332 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002333 }
Robert Greenwaltec8a9e62013-05-23 18:33:06 -07002334 } else {
2335 loge("Can't reset connection for type "+netType);
Robert Greenwalt8d777252011-08-15 12:31:55 -07002336 }
Robert Greenwalt36ea8692011-06-15 12:22:07 -07002337 }
2338 }
2339 }
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002340
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002341 // Update 464xlat state.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002342 NetworkStateTracker tracker = mNetTrackers[netType];
2343 if (mClat.requiresClat(netType, tracker)) {
Lorenzo Colitti7e5624b2013-03-28 14:13:43 +09002344 // If the connection was previously using clat, but is not using it now, stop the clat
2345 // daemon. Normally, this happens automatically when the connection disconnects, but if
2346 // the disconnect is not reported, or if the connection's LinkProperties changed for
2347 // some other reason (e.g., handoff changes the IP addresses on the link), it would
2348 // still be running. If it's not running, then stopping it is a no-op.
2349 if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2350 mClat.stopClat();
2351 }
2352 // If the link requires clat to be running, then start the daemon now.
Lorenzo Colitti5355abd2013-03-15 04:22:37 +09002353 if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2354 mClat.startClat(tracker);
2355 } else {
2356 mClat.stopClat();
2357 }
2358 }
2359
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002360 // TODO: Temporary notifying upstread change to Tethering.
2361 // @see bug/4455071
2362 /** Notify TetheringService if interface name has been changed. */
2363 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
Wink Saville64e3f782012-07-10 12:37:54 -07002364 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002365 if (isTetheringSupported()) {
2366 mTethering.handleTetherIfaceChange();
2367 }
2368 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002369 }
2370
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002371 /**
2372 * Add and remove routes using the old properties (null if not previously connected),
2373 * new properties (null if becoming disconnected). May even be double null, which
2374 * is a noop.
2375 * Uses isLinkDefault to determine if default routes should be set or conversely if
2376 * host routes should be set to the dns servers
Robert Greenwalt8d777252011-08-15 12:31:55 -07002377 * returns a boolean indicating the routes changed
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002378 */
Robert Greenwalt8d777252011-08-15 12:31:55 -07002379 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2380 boolean isLinkDefault) {
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002381 Collection<RouteInfo> routesToAdd = null;
Robert Greenwalt98107422011-07-22 11:55:33 -07002382 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2383 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002384 if (curLp != null) {
2385 // check for the delta between the current set and the new
Robert Greenwalt98107422011-07-22 11:55:33 -07002386 routeDiff = curLp.compareRoutes(newLp);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002387 dnsDiff = curLp.compareDnses(newLp);
Robert Greenwalt98107422011-07-22 11:55:33 -07002388 } else if (newLp != null) {
Lorenzo Colittif5a77d82013-03-15 13:58:38 +09002389 routeDiff.added = newLp.getAllRoutes();
Robert Greenwalt98107422011-07-22 11:55:33 -07002390 dnsDiff.added = newLp.getDnses();
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002391 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002392
Robert Greenwalt8d777252011-08-15 12:31:55 -07002393 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2394
Robert Greenwalt98107422011-07-22 11:55:33 -07002395 for (RouteInfo r : routeDiff.removed) {
2396 if (isLinkDefault || ! r.isDefaultRoute()) {
Robert Greenwalt49c75d32011-11-02 14:37:19 -07002397 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2398 }
2399 if (isLinkDefault == false) {
2400 // remove from a secondary route table
2401 removeRoute(curLp, r, TO_SECONDARY_TABLE);
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002402 }
Robert Greenwalt98107422011-07-22 11:55:33 -07002403 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002404
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002405 if (!isLinkDefault) {
2406 // handle DNS routes
Robert Greenwalt8d777252011-08-15 12:31:55 -07002407 if (routesChanged) {
Robert Greenwalt98107422011-07-22 11:55:33 -07002408 // routes changed - remove all old dns entries and add new
2409 if (curLp != null) {
2410 for (InetAddress oldDns : curLp.getDnses()) {
2411 removeRouteToAddress(curLp, oldDns);
2412 }
2413 }
2414 if (newLp != null) {
2415 for (InetAddress newDns : newLp.getDnses()) {
2416 addRouteToAddress(newLp, newDns);
2417 }
Robert Greenwalt03d53da2011-03-22 18:47:42 -07002418 }
Robert Greenwalt8d777252011-08-15 12:31:55 -07002419 } else {
2420 // no change in routes, check for change in dns themselves
2421 for (InetAddress oldDns : dnsDiff.removed) {
2422 removeRouteToAddress(curLp, oldDns);
2423 }
2424 for (InetAddress newDns : dnsDiff.added) {
2425 addRouteToAddress(newLp, newDns);
2426 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002427 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002428 }
Robert Greenwalt921bf382013-04-05 16:49:32 -07002429
2430 for (RouteInfo r : routeDiff.added) {
2431 if (isLinkDefault || ! r.isDefaultRoute()) {
2432 addRoute(newLp, r, TO_DEFAULT_TABLE);
2433 } else {
2434 // add to a secondary route table
2435 addRoute(newLp, r, TO_SECONDARY_TABLE);
2436
2437 // many radios add a default route even when we don't want one.
2438 // remove the default route unless somebody else has asked for it
2439 String ifaceName = newLp.getInterfaceName();
2440 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2441 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2442 try {
2443 mNetd.removeRoute(ifaceName, r);
2444 } catch (Exception e) {
2445 // never crash - catch them all
2446 if (DBG) loge("Exception trying to remove a route: " + e);
2447 }
2448 }
2449 }
2450 }
2451
Robert Greenwalt8d777252011-08-15 12:31:55 -07002452 return routesChanged;
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002453 }
2454
2455
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002456 /**
2457 * Reads the network specific TCP buffer sizes from SystemProperties
2458 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2459 * wide use
2460 */
Robert Greenwalt26744a52013-02-15 10:56:35 -08002461 private void updateNetworkSettings(NetworkStateTracker nt) {
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002462 String key = nt.getTcpBufferSizesPropName();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002463 String bufferSizes = key == null ? null : SystemProperties.get(key);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002464
Jeff Sharkey02e14d92012-08-04 15:24:58 -07002465 if (TextUtils.isEmpty(bufferSizes)) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002466 if (VDBG) log(key + " not found in system properties. Using defaults");
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002467
2468 // Setting to default values so we won't be stuck to previous values
2469 key = "net.tcp.buffersize.default";
2470 bufferSizes = SystemProperties.get(key);
2471 }
2472
2473 // Set values in kernel
2474 if (bufferSizes.length() != 0) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002475 if (VDBG) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002476 log("Setting TCP values: [" + bufferSizes
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002477 + "] which comes from [" + key + "]");
2478 }
2479 setBufferSize(bufferSizes);
2480 }
2481 }
2482
2483 /**
2484 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2485 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2486 *
2487 * @param bufferSizes in the format of "readMin, readInitial, readMax,
2488 * writeMin, writeInitial, writeMax"
2489 */
2490 private void setBufferSize(String bufferSizes) {
2491 try {
2492 String[] values = bufferSizes.split(",");
2493
2494 if (values.length == 6) {
2495 final String prefix = "/sys/kernel/ipv4/tcp_";
Mike Lockwood0d5916c2011-05-28 13:24:04 -04002496 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2497 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2498 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2499 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2500 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2501 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002502 } else {
Wink Savillee70c6f52010-12-03 12:01:38 -08002503 loge("Invalid buffersize string: " + bufferSizes);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002504 }
2505 } catch (IOException e) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002506 loge("Can't set tcp buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002507 }
2508 }
2509
Robert Greenwalt2034b912009-08-12 16:08:25 -07002510 /**
2511 * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2512 * on the highest priority active net which this process requested.
2513 * If there aren't any, clear it out
2514 */
Mattias Falkdc919012011-08-23 14:15:13 +02002515 private void reassessPidDns(int pid, boolean doBump)
Robert Greenwalt2034b912009-08-12 16:08:25 -07002516 {
Mattias Falkdc919012011-08-23 14:15:13 +02002517 if (VDBG) log("reassessPidDns for pid " + pid);
2518 Integer myPid = new Integer(pid);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002519 for(int i : mPriorityList) {
Robert Greenwalt34848c02011-03-25 13:09:25 -07002520 if (mNetConfigs[i].isDefault()) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002521 continue;
2522 }
2523 NetworkStateTracker nt = mNetTrackers[i];
Robert Greenwalt0659da32009-07-16 17:21:39 -07002524 if (nt.getNetworkInfo().isConnected() &&
2525 !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002526 LinkProperties p = nt.getLinkProperties();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002527 if (p == null) continue;
Mattias Falkdc919012011-08-23 14:15:13 +02002528 if (mNetRequestersPids[i].contains(myPid)) {
2529 try {
2530 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2531 } catch (Exception e) {
2532 Slog.e(TAG, "exception reasseses pid dns: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002533 }
Mattias Falkdc919012011-08-23 14:15:13 +02002534 return;
Robert Greenwalt2034b912009-08-12 16:08:25 -07002535 }
2536 }
2537 }
2538 // nothing found - delete
Mattias Falkdc919012011-08-23 14:15:13 +02002539 try {
2540 mNetd.clearDnsInterfaceForPid(pid);
2541 } catch (Exception e) {
2542 Slog.e(TAG, "exception clear interface from pid: " + e);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002543 }
2544 }
2545
Mattias Falkdc919012011-08-23 14:15:13 +02002546 private void flushVmDnsCache() {
Robert Greenwalt051642b2010-11-02 14:08:23 -07002547 /*
2548 * Tell the VMs to toss their DNS caches
2549 */
2550 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2551 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnuttf444f502011-01-05 17:14:03 -08002552 /*
2553 * Connectivity events can happen before boot has completed ...
2554 */
2555 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07002556 final long ident = Binder.clearCallingIdentity();
2557 try {
2558 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2559 } finally {
2560 Binder.restoreCallingIdentity(ident);
2561 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002562 }
2563
Chia-chi Yehcc844502011-07-14 18:01:57 -07002564 // Caller must grab mDnsLock.
Mattias Falkdc919012011-08-23 14:15:13 +02002565 private void updateDnsLocked(String network, String iface,
Lorenzo Colittiaa035382011-09-28 22:31:45 -07002566 Collection<InetAddress> dnses, String domains) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002567 int last = 0;
2568 if (dnses.size() == 0 && mDefaultDns != null) {
Mattias Falkdc919012011-08-23 14:15:13 +02002569 dnses = new ArrayList();
2570 dnses.add(mDefaultDns);
2571 if (DBG) {
2572 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002573 }
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002574 }
2575
Mattias Falkdc919012011-08-23 14:15:13 +02002576 try {
2577 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2578 mNetd.setDefaultInterfaceForDns(iface);
Robert Greenwaltd44340d2013-02-11 15:25:10 -08002579 for (InetAddress dns : dnses) {
2580 ++last;
2581 String key = "net.dns" + last;
2582 String value = dns.getHostAddress();
2583 SystemProperties.set(key, value);
2584 }
2585 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2586 String key = "net.dns" + i;
2587 SystemProperties.set(key, "");
2588 }
2589 mNumDnsEntries = last;
Mattias Falkdc919012011-08-23 14:15:13 +02002590 } catch (Exception e) {
2591 if (DBG) loge("exception setting default dns interface: " + e);
Robert Greenwaltb16bf0d2013-01-19 00:34:07 +00002592 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002593 }
2594
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002595 private void handleDnsConfigurationChange(int netType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002596 // add default net's dns entries
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002597 NetworkStateTracker nt = mNetTrackers[netType];
2598 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
Robert Greenwalt1f1bcfe2010-08-30 10:56:47 -07002599 LinkProperties p = nt.getLinkProperties();
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002600 if (p == null) return;
2601 Collection<InetAddress> dnses = p.getDnses();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002602 if (mNetConfigs[netType].isDefault()) {
Chia-chi Yehcc844502011-07-14 18:01:57 -07002603 String network = nt.getNetworkInfo().getTypeName();
2604 synchronized (mDnsLock) {
2605 if (!mDnsOverridden) {
Mattias Falkdc919012011-08-23 14:15:13 +02002606 updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
Robert Greenwalt94daa182010-09-01 11:34:05 -07002607 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002608 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002609 } else {
Robert Greenwaltfce71862011-07-25 16:06:25 -07002610 try {
Robert Greenwalt49f762e2011-07-27 10:00:36 -07002611 mNetd.setDnsServersForInterface(p.getInterfaceName(),
Robert Greenwalt0bc6c962012-11-09 10:52:27 -08002612 NetworkUtils.makeStrings(dnses), p.getDomains());
Robert Greenwaltfce71862011-07-25 16:06:25 -07002613 } catch (Exception e) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002614 if (DBG) loge("exception setting dns servers: " + e);
Robert Greenwaltfce71862011-07-25 16:06:25 -07002615 }
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002616 // set per-pid dns for attached secondary nets
Mattias Falkdc919012011-08-23 14:15:13 +02002617 List<Integer> pids = mNetRequestersPids[netType];
2618 for (Integer pid : pids) {
2619 try {
2620 mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2621 } catch (Exception e) {
2622 Slog.e(TAG, "exception setting interface for pid: " + e);
2623 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002624 }
2625 }
Mattias Falkdc919012011-08-23 14:15:13 +02002626 flushVmDnsCache();
The Android Open Source Project28527d22009-03-03 19:31:44 -08002627 }
Robert Greenwalt2034b912009-08-12 16:08:25 -07002628 }
2629
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002630 private int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt2034b912009-08-12 16:08:25 -07002631 String restoreDefaultNetworkDelayStr = SystemProperties.get(
2632 NETWORK_RESTORE_DELAY_PROP_NAME);
2633 if(restoreDefaultNetworkDelayStr != null &&
2634 restoreDefaultNetworkDelayStr.length() != 0) {
2635 try {
2636 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2637 } catch (NumberFormatException e) {
2638 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002639 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002640 // if the system property isn't set, use the value for the apn type
2641 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2642
2643 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2644 (mNetConfigs[networkType] != null)) {
2645 ret = mNetConfigs[networkType].restoreTime;
2646 }
2647 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002648 }
2649
2650 @Override
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002651 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2652 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt0659da32009-07-16 17:21:39 -07002653 if (mContext.checkCallingOrSelfPermission(
2654 android.Manifest.permission.DUMP)
The Android Open Source Project28527d22009-03-03 19:31:44 -08002655 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002656 pw.println("Permission Denial: can't dump ConnectivityService " +
2657 "from from pid=" + Binder.getCallingPid() + ", uid=" +
2658 Binder.getCallingUid());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002659 return;
2660 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002661
2662 // TODO: add locking to get atomic snapshot
The Android Open Source Project28527d22009-03-03 19:31:44 -08002663 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002664 for (int i = 0; i < mNetTrackers.length; i++) {
2665 final NetworkStateTracker nst = mNetTrackers[i];
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002666 if (nst != null) {
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002667 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2668 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002669 if (nst.getNetworkInfo().isConnected()) {
2670 pw.println("Active network: " + nst.getNetworkInfo().
2671 getTypeName());
2672 }
2673 pw.println(nst.getNetworkInfo());
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002674 pw.println(nst.getLinkProperties());
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002675 pw.println(nst);
2676 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002677 pw.decreaseIndent();
Robert Greenwalt2034b912009-08-12 16:08:25 -07002678 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002679 }
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002680
2681 pw.println("Network Requester Pids:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002682 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002683 for (int net : mPriorityList) {
2684 String pidString = net + ": ";
Mattias Falkdc919012011-08-23 14:15:13 +02002685 for (Integer pid : mNetRequestersPids[net]) {
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002686 pidString = pidString + pid.toString() + ", ";
2687 }
2688 pw.println(pidString);
2689 }
2690 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002691 pw.decreaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002692
2693 pw.println("FeatureUsers:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002694 pw.increaseIndent();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08002695 for (Object requester : mFeatureUsers) {
2696 pw.println(requester.toString());
2697 }
2698 pw.println();
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002699 pw.decreaseIndent();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002700
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002701 synchronized (this) {
2702 pw.println("NetworkTranstionWakeLock is currently " +
2703 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2704 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2705 }
2706 pw.println();
2707
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002708 mTethering.dump(fd, pw, args);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002709
2710 if (mInetLog != null) {
2711 pw.println();
2712 pw.println("Inet condition reports:");
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002713 pw.increaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002714 for(int i = 0; i < mInetLog.size(); i++) {
2715 pw.println(mInetLog.get(i));
2716 }
Jeff Sharkeyf58fbae2012-09-14 13:47:51 -07002717 pw.decreaseIndent();
Robert Greenwalt0e80be12010-09-20 14:35:25 -07002718 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002719 }
2720
Robert Greenwalt2034b912009-08-12 16:08:25 -07002721 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002722 private class NetworkStateTrackerHandler extends Handler {
2723 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07002724 super(looper);
2725 }
2726
The Android Open Source Project28527d22009-03-03 19:31:44 -08002727 @Override
2728 public void handleMessage(Message msg) {
2729 NetworkInfo info;
2730 switch (msg.what) {
2731 case NetworkStateTracker.EVENT_STATE_CHANGED:
2732 info = (NetworkInfo) msg.obj;
Robert Greenwalt12c44552009-12-07 11:33:18 -08002733 int type = info.getType();
2734 NetworkInfo.State state = info.getState();
Robert Greenwalt12c44552009-12-07 11:33:18 -08002735
Wink Savillea7d56572011-09-21 11:05:43 -07002736 if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2737 (state == NetworkInfo.State.DISCONNECTED)) {
2738 log("ConnectivityChange for " +
Robert Greenwalt0659da32009-07-16 17:21:39 -07002739 info.getTypeName() + ": " +
Robert Greenwalt12c44552009-12-07 11:33:18 -08002740 state + "/" + info.getDetailedState());
Wink Savillea7d56572011-09-21 11:05:43 -07002741 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002742
Wink Saville9564f2b2013-07-16 17:16:37 -07002743 // After booting we'll check once for mobile provisioning
2744 // if we've provisioned by and connected.
2745 if (!mFirstProvisioningCheckStarted
2746 && (0 != Settings.Global.getInt(mContext.getContentResolver(),
2747 Settings.Global.DEVICE_PROVISIONED, 0))
2748 && (state == NetworkInfo.State.CONNECTED)) {
2749 log("check provisioning after booting");
2750 mFirstProvisioningCheckStarted = true;
2751 checkMobileProvisioning(true, CheckMp.MAX_TIMEOUT_MS, null);
2752 }
2753
Jeff Sharkeybde32692012-11-09 15:57:02 -08002754 EventLogTags.writeConnectivityStateChanged(
2755 info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
Robert Greenwalt0659da32009-07-16 17:21:39 -07002756
2757 if (info.getDetailedState() ==
2758 NetworkInfo.DetailedState.FAILED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002759 handleConnectionFailure(info);
Irfan Sheriffba8388b2012-08-16 12:49:23 -07002760 } else if (info.getDetailedState() ==
2761 DetailedState.CAPTIVE_PORTAL_CHECK) {
2762 handleCaptivePortalTrackerCheck(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002763 } else if (state == NetworkInfo.State.DISCONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002764 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002765 } else if (state == NetworkInfo.State.SUSPENDED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002766 // TODO: need to think this over.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002767 // the logic here is, handle SUSPENDED the same as
2768 // DISCONNECTED. The only difference being we are
2769 // broadcasting an intent with NetworkInfo that's
2770 // suspended. This allows the applications an
2771 // opportunity to handle DISCONNECTED and SUSPENDED
2772 // differently, or not.
The Android Open Source Project28527d22009-03-03 19:31:44 -08002773 handleDisconnect(info);
Robert Greenwalt12c44552009-12-07 11:33:18 -08002774 } else if (state == NetworkInfo.State.CONNECTED) {
The Android Open Source Project28527d22009-03-03 19:31:44 -08002775 handleConnect(info);
2776 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002777 if (mLockdownTracker != null) {
2778 mLockdownTracker.onNetworkInfoChanged(info);
2779 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002780 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002781 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
Robert Greenwalt3afbead2010-07-23 15:46:26 -07002782 info = (NetworkInfo) msg.obj;
Kazuhiro Ondo07680062011-06-22 21:10:34 -05002783 // TODO: Temporary allowing network configuration
2784 // change not resetting sockets.
2785 // @see bug/4455071
2786 handleConnectivityChange(info.getType(), false);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002787 break;
Robert Greenwaltf90d00e2012-08-20 11:15:39 -07002788 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2789 info = (NetworkInfo) msg.obj;
2790 type = info.getType();
2791 updateNetworkSettings(mNetTrackers[type]);
2792 break;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002793 }
2794 }
2795 }
2796
2797 private class InternalHandler extends Handler {
2798 public InternalHandler(Looper looper) {
2799 super(looper);
2800 }
2801
2802 @Override
2803 public void handleMessage(Message msg) {
2804 NetworkInfo info;
2805 switch (msg.what) {
Robert Greenwaltccb36f92010-09-24 14:32:21 -07002806 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002807 String causedBy = null;
2808 synchronized (ConnectivityService.this) {
2809 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2810 mNetTransitionWakeLock.isHeld()) {
2811 mNetTransitionWakeLock.release();
2812 causedBy = mNetTransitionWakeLockCausedBy;
2813 }
2814 }
2815 if (causedBy != null) {
Wink Savillee70c6f52010-12-03 12:01:38 -08002816 log("NetTransition Wakelock for " + causedBy + " released by timeout");
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002817 }
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07002818 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002819 case EVENT_RESTORE_DEFAULT_NETWORK:
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002820 FeatureUser u = (FeatureUser)msg.obj;
2821 u.expire();
Robert Greenwalt986c7412010-09-08 15:24:47 -07002822 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002823 case EVENT_INET_CONDITION_CHANGE:
2824 {
2825 int netType = msg.arg1;
2826 int condition = msg.arg2;
2827 handleInetConditionChange(netType, condition);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002828 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002829 }
2830 case EVENT_INET_CONDITION_HOLD_END:
2831 {
2832 int netType = msg.arg1;
2833 int sequence = msg.arg2;
Wink Saville3e866722013-01-31 00:30:13 +00002834 handleInetConditionHoldEnd(netType, sequence);
Robert Greenwalt986c7412010-09-08 15:24:47 -07002835 break;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002836 }
2837 case EVENT_SET_NETWORK_PREFERENCE:
2838 {
2839 int preference = msg.arg1;
2840 handleSetNetworkPreference(preference);
2841 break;
2842 }
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07002843 case EVENT_SET_MOBILE_DATA:
2844 {
2845 boolean enabled = (msg.arg1 == ENABLED);
2846 handleSetMobileData(enabled);
2847 break;
2848 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002849 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2850 {
2851 handleDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07002852 break;
2853 }
2854 case EVENT_SET_DEPENDENCY_MET:
2855 {
2856 boolean met = (msg.arg1 == ENABLED);
2857 handleSetDependencyMet(msg.arg2, met);
2858 break;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07002859 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07002860 case EVENT_RESTORE_DNS:
2861 {
2862 if (mActiveDefaultNetwork != -1) {
2863 handleDnsConfigurationChange(mActiveDefaultNetwork);
2864 }
2865 break;
2866 }
Wink Saville4f0de1e2011-08-04 15:01:58 -07002867 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2868 {
2869 Intent intent = (Intent)msg.obj;
Wink Saville4f0de1e2011-08-04 15:01:58 -07002870 sendStickyBroadcast(intent);
2871 break;
2872 }
Jeff Sharkey805662d2011-08-19 02:24:24 -07002873 case EVENT_SET_POLICY_DATA_ENABLE: {
2874 final int networkType = msg.arg1;
2875 final boolean enabled = msg.arg2 == ENABLED;
2876 handleSetPolicyDataEnable(networkType, enabled);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07002877 break;
2878 }
2879 case EVENT_VPN_STATE_CHANGED: {
2880 if (mLockdownTracker != null) {
2881 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2882 }
2883 break;
Jeff Sharkey805662d2011-08-19 02:24:24 -07002884 }
Wink Saville690cb182013-06-29 21:10:57 -07002885 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2886 int tag = mEnableFailFastMobileDataTag.get();
2887 if (msg.arg1 == tag) {
2888 MobileDataStateTracker mobileDst =
2889 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2890 if (mobileDst != null) {
2891 mobileDst.setEnableFailFastMobileData(msg.arg2);
2892 }
2893 } else {
2894 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2895 + " != tag:" + tag);
2896 }
2897 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002898 }
2899 }
2900 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002901
2902 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002903 public int tether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002904 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002905
2906 if (isTetheringSupported()) {
2907 return mTethering.tether(iface);
2908 } else {
2909 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2910 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002911 }
2912
2913 // javadoc from interface
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002914 public int untether(String iface) {
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002915 enforceTetherChangePermission();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002916
2917 if (isTetheringSupported()) {
2918 return mTethering.untether(iface);
2919 } else {
2920 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2921 }
2922 }
2923
2924 // javadoc from interface
2925 public int getLastTetherError(String iface) {
2926 enforceTetherAccessPermission();
2927
2928 if (isTetheringSupported()) {
2929 return mTethering.getLastTetherError(iface);
2930 } else {
2931 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2932 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002933 }
2934
2935 // TODO - proper iface API for selection by property, inspection, etc
2936 public String[] getTetherableUsbRegexs() {
2937 enforceTetherAccessPermission();
2938 if (isTetheringSupported()) {
2939 return mTethering.getTetherableUsbRegexs();
2940 } else {
2941 return new String[0];
2942 }
2943 }
2944
2945 public String[] getTetherableWifiRegexs() {
2946 enforceTetherAccessPermission();
2947 if (isTetheringSupported()) {
2948 return mTethering.getTetherableWifiRegexs();
2949 } else {
2950 return new String[0];
2951 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002952 }
2953
Danica Chang96567052010-08-11 14:54:43 -07002954 public String[] getTetherableBluetoothRegexs() {
2955 enforceTetherAccessPermission();
2956 if (isTetheringSupported()) {
2957 return mTethering.getTetherableBluetoothRegexs();
2958 } else {
2959 return new String[0];
2960 }
2961 }
2962
Mike Lockwooded4a1742011-07-19 13:04:47 -07002963 public int setUsbTethering(boolean enable) {
Robert Greenwalt26744a52013-02-15 10:56:35 -08002964 enforceTetherChangePermission();
Mike Lockwooded4a1742011-07-19 13:04:47 -07002965 if (isTetheringSupported()) {
2966 return mTethering.setUsbTethering(enable);
2967 } else {
2968 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2969 }
2970 }
2971
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002972 // TODO - move iface listing, queries, etc to new module
2973 // javadoc from interface
2974 public String[] getTetherableIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002975 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002976 return mTethering.getTetherableIfaces();
2977 }
2978
2979 public String[] getTetheredIfaces() {
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002980 enforceTetherAccessPermission();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08002981 return mTethering.getTetheredIfaces();
2982 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002983
Jeff Sharkey300f08f2011-09-16 01:52:49 -07002984 @Override
2985 public String[] getTetheredIfacePairs() {
2986 enforceTetherAccessPermission();
2987 return mTethering.getTetheredIfacePairs();
2988 }
2989
Robert Greenwalt4283ded2010-03-02 17:25:02 -08002990 public String[] getTetheringErroredIfaces() {
2991 enforceTetherAccessPermission();
2992 return mTethering.getErroredIfaces();
2993 }
2994
Robert Greenwalt8e87f122010-02-11 18:18:40 -08002995 // if ro.tether.denied = true we default to no tethering
2996 // gservices could set the secure setting to 1 though to enable it on a build where it
2997 // had previously been turned off.
2998 public boolean isTetheringSupported() {
2999 enforceTetherAccessPermission();
3000 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brown87272712012-09-25 15:03:20 -07003001 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3002 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
Robert Greenwalt81b02742013-07-18 14:24:42 -07003003 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3004 mTethering.getTetherableWifiRegexs().length != 0 ||
3005 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3006 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003007 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003008
3009 // An API NetworkStateTrackers can call when they lose their network.
3010 // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3011 // whichever happens first. The timer is started by the first caller and not
3012 // restarted by subsequent callers.
3013 public void requestNetworkTransitionWakelock(String forWhom) {
3014 enforceConnectivityInternalPermission();
3015 synchronized (this) {
3016 if (mNetTransitionWakeLock.isHeld()) return;
3017 mNetTransitionWakeLockSerialNumber++;
3018 mNetTransitionWakeLock.acquire();
3019 mNetTransitionWakeLockCausedBy = forWhom;
3020 }
3021 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwaltccb36f92010-09-24 14:32:21 -07003022 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
Robert Greenwalt93dc1042010-06-15 12:19:37 -07003023 mNetTransitionWakeLockSerialNumber, 0),
3024 mNetTransitionWakeLockTimeout);
3025 return;
3026 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07003027
Robert Greenwalt986c7412010-09-08 15:24:47 -07003028 // 100 percent is full good, 0 is full bad.
3029 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003030 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
Robert Greenwalt986c7412010-09-08 15:24:47 -07003031 mContext.enforceCallingOrSelfPermission(
3032 android.Manifest.permission.STATUS_BAR,
3033 "ConnectivityService");
3034
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003035 if (DBG) {
3036 int pid = getCallingPid();
3037 int uid = getCallingUid();
3038 String s = pid + "(" + uid + ") reports inet is " +
3039 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3040 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3041 mInetLog.add(s);
3042 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3043 mInetLog.remove(0);
3044 }
3045 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003046 mHandler.sendMessage(mHandler.obtainMessage(
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003047 EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3048 }
3049
3050 private void handleInetConditionChange(int netType, int condition) {
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003051 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003052 if (DBG) log("handleInetConditionChange: no active default network - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003053 return;
3054 }
3055 if (mActiveDefaultNetwork != netType) {
Wink Savillea7d56572011-09-21 11:05:43 -07003056 if (DBG) log("handleInetConditionChange: net=" + netType +
3057 " != default=" + mActiveDefaultNetwork + " - ignore");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003058 return;
3059 }
Wink Savillea7d56572011-09-21 11:05:43 -07003060 if (VDBG) {
3061 log("handleInetConditionChange: net=" +
3062 netType + ", condition=" + condition +
Wink Saville3e866722013-01-31 00:30:13 +00003063 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
Wink Savillea7d56572011-09-21 11:05:43 -07003064 }
Wink Saville3e866722013-01-31 00:30:13 +00003065 mDefaultInetCondition = condition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003066 int delay;
3067 if (mInetConditionChangeInFlight == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003068 if (VDBG) log("handleInetConditionChange: starting a change hold");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003069 // setup a new hold to debounce this
Wink Saville3e866722013-01-31 00:30:13 +00003070 if (mDefaultInetCondition > 50) {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003071 delay = Settings.Global.getInt(mContext.getContentResolver(),
3072 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003073 } else {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003074 delay = Settings.Global.getInt(mContext.getContentResolver(),
3075 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003076 }
3077 mInetConditionChangeInFlight = true;
3078 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
Wink Saville3e866722013-01-31 00:30:13 +00003079 mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003080 } else {
Wink Savillea7d56572011-09-21 11:05:43 -07003081 // we've set the new condition, when this hold ends that will get picked up
3082 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003083 }
3084 }
3085
Wink Saville3e866722013-01-31 00:30:13 +00003086 private void handleInetConditionHoldEnd(int netType, int sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003087 if (DBG) {
Wink Saville3e866722013-01-31 00:30:13 +00003088 log("handleInetConditionHoldEnd: net=" + netType +
3089 ", condition=" + mDefaultInetCondition +
3090 ", published condition=" + mDefaultInetConditionPublished);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003091 }
3092 mInetConditionChangeInFlight = false;
3093
3094 if (mActiveDefaultNetwork == -1) {
Wink Savillea7d56572011-09-21 11:05:43 -07003095 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003096 return;
3097 }
3098 if (mDefaultConnectionSequence != sequence) {
Wink Savillea7d56572011-09-21 11:05:43 -07003099 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003100 return;
3101 }
Wink Saville3e866722013-01-31 00:30:13 +00003102 // TODO: Figure out why this optimization sometimes causes a
3103 // change in mDefaultInetCondition to be missed and the
3104 // UI to not be updated.
3105 //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3106 // if (DBG) log("no change in condition - aborting");
3107 // return;
3108 //}
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003109 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3110 if (networkInfo.isConnected() == false) {
Wink Savillea7d56572011-09-21 11:05:43 -07003111 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003112 return;
3113 }
Wink Saville3e866722013-01-31 00:30:13 +00003114 mDefaultInetConditionPublished = mDefaultInetCondition;
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07003115 sendInetConditionBroadcast(networkInfo);
3116 return;
Robert Greenwalt986c7412010-09-08 15:24:47 -07003117 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003118
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003119 public ProxyProperties getProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003120 // this information is already available as a world read/writable jvm property
3121 // so this API change wouldn't have a benifit. It also breaks the passing
3122 // of proxy info to all the JVMs.
3123 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003124 synchronized (mProxyLock) {
3125 if (mGlobalProxy != null) return mGlobalProxy;
3126 return (mDefaultProxyDisabled ? null : mDefaultProxy);
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003127 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003128 }
3129
3130 public void setGlobalProxy(ProxyProperties proxyProperties) {
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003131 enforceConnectivityInternalPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003132 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003133 if (proxyProperties == mGlobalProxy) return;
3134 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3135 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3136
3137 String host = "";
3138 int port = 0;
3139 String exclList = "";
3140 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
Raj Mamadgi6bc5eda2013-11-11 13:52:58 -08003141 if (!proxyProperties.isValid()) {
3142 if (DBG)
3143 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3144 return;
3145 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003146 mGlobalProxy = new ProxyProperties(proxyProperties);
3147 host = mGlobalProxy.getHost();
3148 port = mGlobalProxy.getPort();
3149 exclList = mGlobalProxy.getExclusionList();
3150 } else {
3151 mGlobalProxy = null;
3152 }
3153 ContentResolver res = mContext.getContentResolver();
Robert Greenwaltaa4677c2013-04-10 15:32:18 -07003154 final long token = Binder.clearCallingIdentity();
3155 try {
3156 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3157 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3158 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3159 exclList);
3160 } finally {
3161 Binder.restoreCallingIdentity(token);
3162 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003163 }
3164
3165 if (mGlobalProxy == null) {
3166 proxyProperties = mDefaultProxy;
3167 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003168 sendProxyBroadcast(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003169 }
3170
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003171 private void loadGlobalProxy() {
3172 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003173 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3174 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3175 String exclList = Settings.Global.getString(res,
3176 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003177 if (!TextUtils.isEmpty(host)) {
3178 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
Raj Mamadgi6bc5eda2013-11-11 13:52:58 -08003179 if (!proxyProperties.isValid()) {
3180 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3181 return;
3182 }
3183
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003184 synchronized (mProxyLock) {
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08003185 mGlobalProxy = proxyProperties;
3186 }
3187 }
3188 }
3189
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003190 public ProxyProperties getGlobalProxy() {
Robert Greenwaltdc55f482013-02-22 14:57:00 -08003191 // this information is already available as a world read/writable jvm property
3192 // so this API change wouldn't have a benifit. It also breaks the passing
3193 // of proxy info to all the JVMs.
3194 // enforceAccessPermission();
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003195 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003196 return mGlobalProxy;
3197 }
3198 }
3199
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003200 private void handleApplyDefaultProxy(ProxyProperties proxy) {
3201 if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3202 proxy = null;
3203 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003204 synchronized (mProxyLock) {
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003205 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003206 if (mDefaultProxy == proxy) return; // catches repeated nulls
Raj Mamadgi6bc5eda2013-11-11 13:52:58 -08003207 if (!proxy.isValid()) {
3208 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3209 return;
3210 }
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003211 mDefaultProxy = proxy;
3212
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003213 if (mGlobalProxy != null) return;
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003214 if (!mDefaultProxyDisabled) {
3215 sendProxyBroadcast(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003216 }
3217 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003218 }
3219
3220 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003221 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3222 Settings.Global.HTTP_PROXY);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003223 if (!TextUtils.isEmpty(proxy)) {
3224 String data[] = proxy.split(":");
3225 String proxyHost = data[0];
3226 int proxyPort = 8080;
3227 if (data.length > 1) {
3228 try {
3229 proxyPort = Integer.parseInt(data[1]);
3230 } catch (NumberFormatException e) {
3231 return;
3232 }
3233 }
3234 ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3235 setGlobalProxy(p);
3236 }
3237 }
3238
3239 private void sendProxyBroadcast(ProxyProperties proxy) {
Robert Greenwalt611291c2010-12-23 15:51:10 -08003240 if (proxy == null) proxy = new ProxyProperties("", 0, "");
Robert Greenwalt78f28112011-08-02 17:18:41 -07003241 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003242 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnutt1f2a2ac2011-01-06 11:00:19 -08003243 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3244 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003245 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackborn43fb9ba2012-09-04 18:48:37 -07003246 final long ident = Binder.clearCallingIdentity();
3247 try {
3248 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3249 } finally {
3250 Binder.restoreCallingIdentity(ident);
3251 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003252 }
3253
3254 private static class SettingsObserver extends ContentObserver {
3255 private int mWhat;
3256 private Handler mHandler;
3257 SettingsObserver(Handler handler, int what) {
3258 super(handler);
3259 mHandler = handler;
3260 mWhat = what;
3261 }
3262
3263 void observe(Context context) {
3264 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey5eccd9c2012-09-26 22:03:49 -07003265 resolver.registerContentObserver(Settings.Global.getUriFor(
3266 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07003267 }
3268
3269 @Override
3270 public void onChange(boolean selfChange) {
3271 mHandler.obtainMessage(mWhat).sendToTarget();
3272 }
3273 }
Wink Savillee70c6f52010-12-03 12:01:38 -08003274
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003275 private static void log(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003276 Slog.d(TAG, s);
3277 }
3278
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07003279 private static void loge(String s) {
Wink Savillee70c6f52010-12-03 12:01:38 -08003280 Slog.e(TAG, s);
3281 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003282
repo syncf5de5572011-07-29 23:55:49 -07003283 int convertFeatureToNetworkType(int networkType, String feature) {
3284 int usedNetworkType = networkType;
3285
3286 if(networkType == ConnectivityManager.TYPE_MOBILE) {
3287 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3288 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3289 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3290 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3291 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3292 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3293 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3294 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3295 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3296 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3297 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3298 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3299 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3300 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3301 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3302 } else {
3303 Slog.e(TAG, "Can't match any mobile netTracker!");
3304 }
3305 } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3306 if (TextUtils.equals(feature, "p2p")) {
3307 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3308 } else {
3309 Slog.e(TAG, "Can't match any wifi netTracker!");
3310 }
3311 } else {
3312 Slog.e(TAG, "Unexpected network type");
Wink Savillef6b76692011-02-24 17:58:51 -08003313 }
repo syncf5de5572011-07-29 23:55:49 -07003314 return usedNetworkType;
Wink Savillef6b76692011-02-24 17:58:51 -08003315 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003316
3317 private static <T> T checkNotNull(T value, String message) {
3318 if (value == null) {
3319 throw new NullPointerException(message);
3320 }
3321 return value;
3322 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003323
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003324 /**
3325 * Protect a socket from VPN routing rules. This method is used by
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003326 * VpnBuilder and not available in ConnectivityManager. Permissions
3327 * are checked in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003328 * @hide
3329 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003330 @Override
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003331 public boolean protectVpn(ParcelFileDescriptor socket) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003332 throwIfLockdownEnabled();
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003333 try {
3334 int type = mActiveDefaultNetwork;
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003335 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
Chia-chi Yeh9e4ff6e2011-07-14 16:19:19 -07003336 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3337 return true;
3338 }
3339 } catch (Exception e) {
3340 // ignore
3341 } finally {
3342 try {
3343 socket.close();
3344 } catch (Exception e) {
3345 // ignore
3346 }
3347 }
3348 return false;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003349 }
3350
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003351 /**
3352 * Prepare for a VPN application. This method is used by VpnDialogs
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003353 * and not available in ConnectivityManager. Permissions are checked
3354 * in Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003355 * @hide
3356 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003357 @Override
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003358 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003359 throwIfLockdownEnabled();
Chia-chi Yeh3e2e1da2011-07-03 16:52:38 -07003360 return mVpn.prepare(oldPackage, newPackage);
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003361 }
3362
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003363 /**
3364 * Configure a TUN interface and return its file descriptor. Parameters
3365 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003366 * and not available in ConnectivityManager. Permissions are checked in
3367 * Vpn class.
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003368 * @hide
3369 */
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003370 @Override
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07003371 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003372 throwIfLockdownEnabled();
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003373 return mVpn.establish(config);
3374 }
3375
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003376 /**
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003377 * Start legacy VPN, controlling native daemons as needed. Creates a
3378 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003379 */
3380 @Override
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003381 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003382 throwIfLockdownEnabled();
Jeff Sharkeyc2a8e402012-08-24 11:17:25 -07003383 final LinkProperties egress = getActiveLinkProperties();
3384 if (egress == null) {
3385 throw new IllegalStateException("Missing active network connection");
3386 }
3387 mVpn.startLegacyVpn(profile, mKeyStore, egress);
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003388 }
3389
3390 /**
3391 * Return the information of the ongoing legacy VPN. This method is used
3392 * by VpnSettings and not available in ConnectivityManager. Permissions
3393 * are checked in Vpn class.
3394 * @hide
3395 */
3396 @Override
3397 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003398 throwIfLockdownEnabled();
Chia-chi Yehbded3eb2011-07-04 03:23:12 -07003399 return mVpn.getLegacyVpnInfo();
Chia-chi Yeh7e026b32011-07-02 17:15:00 -07003400 }
3401
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003402 /**
3403 * Callback for VPN subsystem. Currently VPN is not adapted to the service
3404 * through NetworkStateTracker since it works differently. For example, it
3405 * needs to override DNS servers but never takes the default routes. It
3406 * relies on another data network, and it could keep existing connections
3407 * alive after reconnecting, switching between networks, or even resuming
3408 * from deep sleep. Calls from applications should be done synchronously
3409 * to avoid race conditions. As these are all hidden APIs, refactoring can
3410 * be done whenever a better abstraction is developed.
3411 */
3412 public class VpnCallback {
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003413 private VpnCallback() {
3414 }
3415
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003416 public void onStateChanged(NetworkInfo info) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003417 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
Jeff Sharkey02e14d92012-08-04 15:24:58 -07003418 }
3419
Chia-chi Yehcc844502011-07-14 18:01:57 -07003420 public void override(List<String> dnsServers, List<String> searchDomains) {
3421 if (dnsServers == null) {
3422 restore();
3423 return;
3424 }
3425
3426 // Convert DNS servers into addresses.
3427 List<InetAddress> addresses = new ArrayList<InetAddress>();
3428 for (String address : dnsServers) {
3429 // Double check the addresses and remove invalid ones.
3430 try {
3431 addresses.add(InetAddress.parseNumericAddress(address));
3432 } catch (Exception e) {
3433 // ignore
3434 }
3435 }
3436 if (addresses.isEmpty()) {
3437 restore();
3438 return;
3439 }
3440
3441 // Concatenate search domains into a string.
3442 StringBuilder buffer = new StringBuilder();
3443 if (searchDomains != null) {
3444 for (String domain : searchDomains) {
3445 buffer.append(domain).append(' ');
3446 }
3447 }
3448 String domains = buffer.toString().trim();
3449
3450 // Apply DNS changes.
Chia-chi Yehcc844502011-07-14 18:01:57 -07003451 synchronized (mDnsLock) {
Mattias Falkdc919012011-08-23 14:15:13 +02003452 updateDnsLocked("VPN", "VPN", addresses, domains);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003453 mDnsOverridden = true;
3454 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003455
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003456 // Temporarily disable the default proxy (not global).
3457 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003458 mDefaultProxyDisabled = true;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003459 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003460 sendProxyBroadcast(null);
3461 }
3462 }
3463
3464 // TODO: support proxy per network.
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003465 }
3466
Chia-chi Yehcc844502011-07-14 18:01:57 -07003467 public void restore() {
3468 synchronized (mDnsLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003469 if (mDnsOverridden) {
3470 mDnsOverridden = false;
3471 mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
Chia-chi Yehcc844502011-07-14 18:01:57 -07003472 }
Chia-chi Yehcc844502011-07-14 18:01:57 -07003473 }
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003474 synchronized (mProxyLock) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003475 mDefaultProxyDisabled = false;
Robert Greenwaltda77cb12013-04-05 17:14:19 -07003476 if (mGlobalProxy == null && mDefaultProxy != null) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07003477 sendProxyBroadcast(mDefaultProxy);
3478 }
3479 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07003480 }
3481 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003482
3483 @Override
3484 public boolean updateLockdownVpn() {
Jeff Sharkeyc8a26872013-01-31 17:22:26 -08003485 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3486 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3487 return false;
3488 }
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003489
3490 // Tear down existing lockdown if profile was removed
3491 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3492 if (mLockdownEnabled) {
Kenny Roote3a37b22013-02-14 10:18:38 -08003493 if (!mKeyStore.isUnlocked()) {
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003494 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3495 return false;
3496 }
3497
3498 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3499 final VpnProfile profile = VpnProfile.decode(
3500 profileName, mKeyStore.get(Credentials.VPN + profileName));
3501 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3502 } else {
3503 setLockdownTracker(null);
3504 }
3505
3506 return true;
3507 }
3508
3509 /**
3510 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3511 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3512 */
3513 private void setLockdownTracker(LockdownVpnTracker tracker) {
3514 // Shutdown any existing tracker
3515 final LockdownVpnTracker existing = mLockdownTracker;
3516 mLockdownTracker = null;
3517 if (existing != null) {
3518 existing.shutdown();
3519 }
3520
3521 try {
3522 if (tracker != null) {
3523 mNetd.setFirewallEnabled(true);
Jeff Sharkeyb103b252013-02-28 16:57:58 -08003524 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkeyf2e722a2012-08-25 00:05:46 -07003525 mLockdownTracker = tracker;
3526 mLockdownTracker.init();
3527 } else {
3528 mNetd.setFirewallEnabled(false);
3529 }
3530 } catch (RemoteException e) {
3531 // ignored; NMS lives inside system_server
3532 }
3533 }
3534
3535 private void throwIfLockdownEnabled() {
3536 if (mLockdownEnabled) {
3537 throw new IllegalStateException("Unavailable in lockdown mode");
3538 }
3539 }
Robert Greenwalt030e1d32012-08-21 19:27:00 -07003540
3541 public void supplyMessenger(int networkType, Messenger messenger) {
3542 enforceConnectivityInternalPermission();
3543
3544 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3545 mNetTrackers[networkType].supplyMessenger(messenger);
3546 }
3547 }
Robert Greenwalt308b9ac2013-04-22 11:13:02 -07003548
3549 public int findConnectionTypeForIface(String iface) {
3550 enforceConnectivityInternalPermission();
3551
3552 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3553 for (NetworkStateTracker tracker : mNetTrackers) {
3554 if (tracker != null) {
3555 LinkProperties lp = tracker.getLinkProperties();
3556 if (lp != null && iface.equals(lp.getInterfaceName())) {
3557 return tracker.getNetworkInfo().getType();
3558 }
3559 }
3560 }
3561 return ConnectivityManager.TYPE_NONE;
3562 }
Wink Saville690cb182013-06-29 21:10:57 -07003563
3564 /**
3565 * Have mobile data fail fast if enabled.
3566 *
3567 * @param enabled DctConstants.ENABLED/DISABLED
3568 */
3569 private void setEnableFailFastMobileData(int enabled) {
3570 int tag;
3571
3572 if (enabled == DctConstants.ENABLED) {
3573 tag = mEnableFailFastMobileDataTag.incrementAndGet();
3574 } else {
3575 tag = mEnableFailFastMobileDataTag.get();
3576 }
3577 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
3578 enabled));
3579 }
3580
3581 @Override
3582 public int checkMobileProvisioning(boolean sendNotification, int suggestedTimeOutMs,
3583 final ResultReceiver resultReceiver) {
3584 log("checkMobileProvisioning: E sendNotification=" + sendNotification
3585 + " suggestedTimeOutMs=" + suggestedTimeOutMs
3586 + " resultReceiver=" + resultReceiver);
3587 enforceChangePermission();
3588
Wink Saville9564f2b2013-07-16 17:16:37 -07003589 mFirstProvisioningCheckStarted = true;
3590
Wink Saville690cb182013-06-29 21:10:57 -07003591 int timeOutMs = suggestedTimeOutMs;
3592 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
3593 timeOutMs = CheckMp.MAX_TIMEOUT_MS;
3594 }
3595
Wink Savillefdb84862013-07-02 10:55:14 -07003596 // Check that mobile networks are supported
3597 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
3598 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
3599 log("checkMobileProvisioning: X no mobile network");
3600 if (resultReceiver != null) {
3601 resultReceiver.send(ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION, null);
3602 }
3603 return timeOutMs;
3604 }
3605
Wink Saville690cb182013-06-29 21:10:57 -07003606 final long token = Binder.clearCallingIdentity();
3607 try {
3608 CheckMp checkMp = new CheckMp(mContext, this);
3609 CheckMp.CallBack cb = new CheckMp.CallBack() {
3610 @Override
3611 void onComplete(Integer result) {
3612 log("CheckMp.onComplete: result=" + result);
3613 if (resultReceiver != null) {
3614 log("CheckMp.onComplete: send result");
3615 resultReceiver.send(result, null);
3616 }
3617 NetworkInfo ni =
3618 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
3619 switch(result) {
3620 case ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE:
3621 case ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION: {
3622 log("CheckMp.onComplete: ignore, connected or no connection");
3623 break;
3624 }
3625 case ConnectivityManager.CMP_RESULT_CODE_REDIRECTED: {
3626 log("CheckMp.onComplete: warm sim");
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07003627 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07003628 if (TextUtils.isEmpty(url)) {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07003629 url = getMobileRedirectedProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07003630 }
3631 if (TextUtils.isEmpty(url) == false) {
3632 log("CheckMp.onComplete: warm sim (redirected), url=" + url);
3633 setNotificationVisible(true, ni, url);
3634 } else {
3635 log("CheckMp.onComplete: warm sim (redirected), no url");
3636 }
3637 break;
3638 }
3639 case ConnectivityManager.CMP_RESULT_CODE_NO_DNS:
3640 case ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION: {
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07003641 String url = getMobileProvisioningUrl();
Wink Saville690cb182013-06-29 21:10:57 -07003642 if (TextUtils.isEmpty(url) == false) {
3643 log("CheckMp.onComplete: warm sim (no dns/tcp), url=" + url);
3644 setNotificationVisible(true, ni, url);
3645 } else {
3646 log("CheckMp.onComplete: warm sim (no dns/tcp), no url");
3647 }
3648 break;
3649 }
3650 default: {
3651 loge("CheckMp.onComplete: ignore unexpected result=" + result);
3652 break;
3653 }
3654 }
3655 }
3656 };
3657 CheckMp.Params params =
3658 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3659 log("checkMobileProvisioning: params=" + params);
3660 setNotificationVisible(false, null, null);
3661 checkMp.execute(params);
3662 } finally {
3663 Binder.restoreCallingIdentity(token);
3664 log("checkMobileProvisioning: X");
3665 }
3666 return timeOutMs;
3667 }
3668
3669 static class CheckMp extends
3670 AsyncTask<CheckMp.Params, Void, Integer> {
3671 private static final String CHECKMP_TAG = "CheckMp";
3672 public static final int MAX_TIMEOUT_MS = 60000;
3673 private static final int SOCKET_TIMEOUT_MS = 5000;
3674 private Context mContext;
3675 private ConnectivityService mCs;
3676 private TelephonyManager mTm;
3677 private Params mParams;
3678
3679 /**
3680 * Parameters for AsyncTask.execute
3681 */
3682 static class Params {
3683 private String mUrl;
3684 private long mTimeOutMs;
3685 private CallBack mCb;
3686
3687 Params(String url, long timeOutMs, CallBack cb) {
3688 mUrl = url;
3689 mTimeOutMs = timeOutMs;
3690 mCb = cb;
3691 }
3692
3693 @Override
3694 public String toString() {
3695 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3696 }
3697 }
3698
3699 /**
3700 * The call back object passed in Params. onComplete will be called
3701 * on the main thread.
3702 */
3703 abstract static class CallBack {
3704 // Called on the main thread.
3705 abstract void onComplete(Integer result);
3706 }
3707
3708 public CheckMp(Context context, ConnectivityService cs) {
3709 mContext = context;
3710 mCs = cs;
3711
3712 // Setup access to TelephonyService we'll be using.
3713 mTm = (TelephonyManager) mContext.getSystemService(
3714 Context.TELEPHONY_SERVICE);
3715 }
3716
3717 /**
3718 * Get the default url to use for the test.
3719 */
3720 public String getDefaultUrl() {
3721 // See http://go/clientsdns for usage approval
3722 String server = Settings.Global.getString(mContext.getContentResolver(),
3723 Settings.Global.CAPTIVE_PORTAL_SERVER);
3724 if (server == null) {
3725 server = "clients3.google.com";
3726 }
3727 return "http://" + server + "/generate_204";
3728 }
3729
3730 /**
3731 * Detect if its possible to connect to the http url. DNS based detection techniques
3732 * do not work at all hotspots. The best way to check is to perform a request to
3733 * a known address that fetches the data we expect.
3734 */
3735 private synchronized Integer isMobileOk(Params params) {
3736 Integer result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3737 Uri orgUri = Uri.parse(params.mUrl);
3738 Random rand = new Random();
3739 mParams = params;
3740
3741 try {
3742 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3743 log("isMobileOk: not mobile capable");
3744 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3745 return result;
3746 }
3747
3748 // Enable fail fast as we'll do retries here and use a
3749 // hipri connection so the default connection stays active.
3750 log("isMobileOk: start hipri url=" + params.mUrl);
3751 mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3752 mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3753 Phone.FEATURE_ENABLE_HIPRI, new Binder());
3754
3755 // Continue trying to connect until time has run out
3756 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3757 while(SystemClock.elapsedRealtime() < endTime) {
3758 try {
3759 // Wait for hipri to connect.
3760 // TODO: Don't poll and handle situation where hipri fails
3761 // because default is retrying. See b/9569540
3762 NetworkInfo.State state = mCs
3763 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3764 if (state != NetworkInfo.State.CONNECTED) {
3765 log("isMobileOk: not connected ni=" +
3766 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3767 sleep(1);
3768 result = ConnectivityManager.CMP_RESULT_CODE_NO_CONNECTION;
3769 continue;
3770 }
3771
3772 // Get of the addresses associated with the url host. We need to use the
3773 // address otherwise HttpURLConnection object will use the name to get
3774 // the addresses and is will try every address but that will bypass the
3775 // route to host we setup and the connection could succeed as the default
3776 // interface might be connected to the internet via wifi or other interface.
3777 InetAddress[] addresses;
3778 try {
3779 addresses = InetAddress.getAllByName(orgUri.getHost());
3780 } catch (UnknownHostException e) {
3781 log("isMobileOk: UnknownHostException");
3782 result = ConnectivityManager.CMP_RESULT_CODE_NO_DNS;
3783 return result;
3784 }
3785 log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3786
3787 // Get the type of addresses supported by this link
3788 LinkProperties lp = mCs.getLinkProperties(
3789 ConnectivityManager.TYPE_MOBILE_HIPRI);
3790 boolean linkHasIpv4 = hasIPv4Address(lp);
3791 boolean linkHasIpv6 = hasIPv6Address(lp);
3792 log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3793 + " linkHasIpv6=" + linkHasIpv6);
3794
3795 // Loop through at most 3 valid addresses or all of the address or until
3796 // we run out of time
3797 int loops = Math.min(3, addresses.length);
3798 for(int validAddr=0, addrTried=0;
3799 (validAddr < loops) && (addrTried < addresses.length)
3800 && (SystemClock.elapsedRealtime() < endTime);
3801 addrTried ++) {
3802
3803 // Choose the address at random but make sure its type is supported
3804 InetAddress hostAddr = addresses[rand.nextInt(addresses.length)];
3805 if (((hostAddr instanceof Inet4Address) && linkHasIpv4)
3806 || ((hostAddr instanceof Inet6Address) && linkHasIpv6)) {
3807 // Valid address, so use it
3808 validAddr += 1;
3809 } else {
3810 // Invalid address so try next address
3811 continue;
3812 }
3813
3814 // Make a route to host so we check the specific interface.
3815 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3816 hostAddr.getAddress())) {
3817 // Wait a short time to be sure the route is established ??
3818 log("isMobileOk:"
3819 + " wait to establish route to hostAddr=" + hostAddr);
3820 sleep(3);
3821 } else {
3822 log("isMobileOk:"
3823 + " could not establish route to hostAddr=" + hostAddr);
3824 continue;
3825 }
3826
3827 // Rewrite the url to have numeric address to use the specific route.
3828 // I also set the "Connection" to "Close" as by default "Keep-Alive"
3829 // is used which is useless in this case.
3830 URL newUrl = new URL(orgUri.getScheme() + "://"
3831 + hostAddr.getHostAddress() + orgUri.getPath());
3832 log("isMobileOk: newUrl=" + newUrl);
3833
3834 HttpURLConnection urlConn = null;
3835 try {
3836 // Open the connection set the request header and get the response
3837 urlConn = (HttpURLConnection) newUrl.openConnection(
3838 java.net.Proxy.NO_PROXY);
3839 urlConn.setInstanceFollowRedirects(false);
3840 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3841 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3842 urlConn.setUseCaches(false);
3843 urlConn.setAllowUserInteraction(false);
3844 urlConn.setRequestProperty("Connection", "close");
3845 int responseCode = urlConn.getResponseCode();
3846 if (responseCode == 204) {
3847 result = ConnectivityManager.CMP_RESULT_CODE_CONNECTABLE;
3848 } else {
3849 result = ConnectivityManager.CMP_RESULT_CODE_REDIRECTED;
3850 }
3851 log("isMobileOk: connected responseCode=" + responseCode);
3852 urlConn.disconnect();
3853 urlConn = null;
3854 return result;
3855 } catch (Exception e) {
3856 log("isMobileOk: HttpURLConnection Exception e=" + e);
3857 if (urlConn != null) {
3858 urlConn.disconnect();
3859 urlConn = null;
3860 }
3861 }
3862 }
3863 result = ConnectivityManager.CMP_RESULT_CODE_NO_TCP_CONNECTION;
3864 log("isMobileOk: loops|timed out");
3865 return result;
3866 } catch (Exception e) {
3867 log("isMobileOk: Exception e=" + e);
3868 continue;
3869 }
3870 }
3871 log("isMobileOk: timed out");
3872 } finally {
3873 log("isMobileOk: F stop hipri");
3874 mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3875 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3876 Phone.FEATURE_ENABLE_HIPRI);
3877 log("isMobileOk: X result=" + result);
3878 }
3879 return result;
3880 }
3881
3882 @Override
3883 protected Integer doInBackground(Params... params) {
3884 return isMobileOk(params[0]);
3885 }
3886
3887 @Override
3888 protected void onPostExecute(Integer result) {
3889 log("onPostExecute: result=" + result);
3890 if ((mParams != null) && (mParams.mCb != null)) {
3891 mParams.mCb.onComplete(result);
3892 }
3893 }
3894
3895 private String inetAddressesToString(InetAddress[] addresses) {
3896 StringBuffer sb = new StringBuffer();
3897 boolean firstTime = true;
3898 for(InetAddress addr : addresses) {
3899 if (firstTime) {
3900 firstTime = false;
3901 } else {
3902 sb.append(",");
3903 }
3904 sb.append(addr);
3905 }
3906 return sb.toString();
3907 }
3908
3909 private void printNetworkInfo() {
3910 boolean hasIccCard = mTm.hasIccCard();
3911 int simState = mTm.getSimState();
3912 log("hasIccCard=" + hasIccCard
3913 + " simState=" + simState);
3914 NetworkInfo[] ni = mCs.getAllNetworkInfo();
3915 if (ni != null) {
3916 log("ni.length=" + ni.length);
3917 for (NetworkInfo netInfo: ni) {
3918 log("netInfo=" + netInfo.toString());
3919 }
3920 } else {
3921 log("no network info ni=null");
3922 }
3923 }
3924
3925 /**
3926 * Sleep for a few seconds then return.
3927 * @param seconds
3928 */
3929 private static void sleep(int seconds) {
3930 try {
3931 Thread.sleep(seconds * 1000);
3932 } catch (InterruptedException e) {
3933 e.printStackTrace();
3934 }
3935 }
3936
3937 public boolean hasIPv4Address(LinkProperties lp) {
3938 return lp.hasIPv4Address();
3939 }
3940
3941 // Not implemented in LinkProperties, do it here.
3942 public boolean hasIPv6Address(LinkProperties lp) {
3943 for (LinkAddress address : lp.getLinkAddresses()) {
3944 if (address.getAddress() instanceof Inet6Address) {
3945 return true;
3946 }
3947 }
3948 return false;
3949 }
3950
3951 private void log(String s) {
3952 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
3953 }
3954 }
3955
3956 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3957
3958 private void setNotificationVisible(boolean visible, NetworkInfo networkInfo, String url) {
3959 log("setNotificationVisible: E visible=" + visible + " ni=" + networkInfo + " url=" + url);
3960
3961 Resources r = Resources.getSystem();
3962 NotificationManager notificationManager = (NotificationManager) mContext
3963 .getSystemService(Context.NOTIFICATION_SERVICE);
3964
3965 if (visible) {
3966 CharSequence title;
3967 CharSequence details;
3968 int icon;
3969 switch (networkInfo.getType()) {
3970 case ConnectivityManager.TYPE_WIFI:
3971 log("setNotificationVisible: TYPE_WIFI");
3972 title = r.getString(R.string.wifi_available_sign_in, 0);
3973 details = r.getString(R.string.network_available_sign_in_detailed,
3974 networkInfo.getExtraInfo());
3975 icon = R.drawable.stat_notify_wifi_in_range;
3976 break;
3977 case ConnectivityManager.TYPE_MOBILE:
3978 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3979 log("setNotificationVisible: TYPE_MOBILE|HIPRI");
3980 title = r.getString(R.string.network_available_sign_in, 0);
3981 // TODO: Change this to pull from NetworkInfo once a printable
3982 // name has been added to it
3983 details = mTelephonyManager.getNetworkOperatorName();
3984 icon = R.drawable.stat_notify_rssi_in_range;
3985 break;
3986 default:
3987 log("setNotificationVisible: other type=" + networkInfo.getType());
3988 title = r.getString(R.string.network_available_sign_in, 0);
3989 details = r.getString(R.string.network_available_sign_in_detailed,
3990 networkInfo.getExtraInfo());
3991 icon = R.drawable.stat_notify_rssi_in_range;
3992 break;
3993 }
3994
3995 Notification notification = new Notification();
3996 notification.when = 0;
3997 notification.icon = icon;
3998 notification.flags = Notification.FLAG_AUTO_CANCEL;
3999 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4000 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4001 Intent.FLAG_ACTIVITY_NEW_TASK);
4002 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4003 notification.tickerText = title;
4004 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4005
4006 log("setNotificaitionVisible: notify notificaiton=" + notification);
4007 notificationManager.notify(NOTIFICATION_ID, 1, notification);
4008 } else {
4009 log("setNotificaitionVisible: cancel");
4010 notificationManager.cancel(NOTIFICATION_ID, 1);
4011 }
4012 log("setNotificationVisible: X visible=" + visible + " ni=" + networkInfo + " url=" + url);
4013 }
4014
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004015 /** Location to an updatable file listing carrier provisioning urls.
4016 * An example:
4017 *
4018 * <?xml version="1.0" encoding="utf-8"?>
4019 * <provisioningUrls>
4020 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
4021 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4022 * </provisioningUrls>
4023 */
4024 private static final String PROVISIONING_URL_PATH =
4025 "/data/misc/radio/provisioning_urls.xml";
4026 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Saville690cb182013-06-29 21:10:57 -07004027
Robert Greenwalt7ddc6c92013-07-16 12:06:09 -07004028 /** XML tag for root element. */
4029 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4030 /** XML tag for individual url */
4031 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4032 /** XML tag for redirected url */
4033 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4034 /** XML attribute for mcc */
4035 private static final String ATTR_MCC = "mcc";
4036 /** XML attribute for mnc */
4037 private static final String ATTR_MNC = "mnc";
4038
4039 private static final int REDIRECTED_PROVISIONING = 1;
4040 private static final int PROVISIONING = 2;
4041
4042 private String getProvisioningUrlBaseFromFile(int type) {
4043 FileReader fileReader = null;
4044 XmlPullParser parser = null;
4045 Configuration config = mContext.getResources().getConfiguration();
4046 String tagType;
4047
4048 switch (type) {
4049 case PROVISIONING:
4050 tagType = TAG_PROVISIONING_URL;
4051 break;
4052 case REDIRECTED_PROVISIONING:
4053 tagType = TAG_REDIRECTED_URL;
4054 break;
4055 default:
4056 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4057 type);
4058 }
4059
4060 try {
4061 fileReader = new FileReader(mProvisioningUrlFile);
4062 parser = Xml.newPullParser();
4063 parser.setInput(fileReader);
4064 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4065
4066 while (true) {
4067 XmlUtils.nextElement(parser);
4068
4069 String element = parser.getName();
4070 if (element == null) break;
4071
4072 if (element.equals(tagType)) {
4073 String mcc = parser.getAttributeValue(null, ATTR_MCC);
4074 try {
4075 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4076 String mnc = parser.getAttributeValue(null, ATTR_MNC);
4077 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
4078 parser.next();
4079 if (parser.getEventType() == XmlPullParser.TEXT) {
4080 return parser.getText();
4081 }
4082 }
4083 }
4084 } catch (NumberFormatException e) {
4085 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
4086 }
4087 }
4088 }
4089 return null;
4090 } catch (FileNotFoundException e) {
4091 loge("Carrier Provisioning Urls file not found");
4092 } catch (XmlPullParserException e) {
4093 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
4094 } catch (IOException e) {
4095 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
4096 } finally {
4097 if (fileReader != null) {
4098 try {
4099 fileReader.close();
4100 } catch (IOException e) {}
4101 }
4102 }
4103 return null;
4104 }
4105
4106 private String getMobileRedirectedProvisioningUrl() {
4107 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
4108 if (TextUtils.isEmpty(url)) {
4109 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
4110 }
4111 return url;
4112 }
4113
4114 public String getMobileProvisioningUrl() {
4115 enforceConnectivityInternalPermission();
4116 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
4117 if (TextUtils.isEmpty(url)) {
4118 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
4119 log("getProvisioningUrl: mobile_provisioining_url from resource =" + url);
4120 } else {
4121 log("getProvisioningUrl: mobile_provisioning_url from File =" + url);
4122 }
Wink Savilledfabd992013-07-10 23:00:07 -07004123 // populate the iccid, imei and phone number in the provisioning url.
Wink Saville690cb182013-06-29 21:10:57 -07004124 if (!TextUtils.isEmpty(url)) {
Wink Savilledfabd992013-07-10 23:00:07 -07004125 String phoneNumber = mTelephonyManager.getLine1Number();
4126 if (TextUtils.isEmpty(phoneNumber)) {
4127 phoneNumber = "0000000000";
4128 }
Wink Saville690cb182013-06-29 21:10:57 -07004129 url = String.format(url,
4130 mTelephonyManager.getSimSerialNumber() /* ICCID */,
4131 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Savilledfabd992013-07-10 23:00:07 -07004132 phoneNumber /* Phone numer */);
Wink Saville690cb182013-06-29 21:10:57 -07004133 }
4134
Wink Saville690cb182013-06-29 21:10:57 -07004135 return url;
4136 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08004137}