ConnectivityService.java revision d5648dcf6a477a350c281c769bae07b8cbe982a3
1/*
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
19import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
20import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
21import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
23import static android.net.ConnectivityManager.NetworkCallbacks;
24import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
25import static android.net.ConnectivityManager.TYPE_DUMMY;
26import static android.net.ConnectivityManager.TYPE_ETHERNET;
27import static android.net.ConnectivityManager.TYPE_MOBILE;
28import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
29import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
30import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
31import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
32import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
33import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
34import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
35import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
36import static android.net.ConnectivityManager.TYPE_NONE;
37import static android.net.ConnectivityManager.TYPE_WIFI;
38import static android.net.ConnectivityManager.TYPE_WIMAX;
39import static android.net.ConnectivityManager.TYPE_PROXY;
40import static android.net.ConnectivityManager.getNetworkTypeName;
41import static android.net.ConnectivityManager.isNetworkTypeValid;
42import static android.net.ConnectivityServiceProtocol.NetworkFactoryProtocol;
43import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
44import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
45
46import android.app.AlarmManager;
47import android.app.AppOpsManager;
48import android.app.Notification;
49import android.app.NotificationManager;
50import android.app.PendingIntent;
51import android.bluetooth.BluetoothTetheringDataTracker;
52import android.content.ActivityNotFoundException;
53import android.content.BroadcastReceiver;
54import android.content.ContentResolver;
55import android.content.Context;
56import android.content.ContextWrapper;
57import android.content.Intent;
58import android.content.IntentFilter;
59import android.content.pm.ApplicationInfo;
60import android.content.pm.PackageManager;
61import android.content.pm.PackageManager.NameNotFoundException;
62import android.content.res.Configuration;
63import android.content.res.Resources;
64import android.database.ContentObserver;
65import android.net.CaptivePortalTracker;
66import android.net.ConnectivityManager;
67import android.net.DummyDataStateTracker;
68import android.net.EthernetDataTracker;
69import android.net.IConnectivityManager;
70import android.net.INetworkManagementEventObserver;
71import android.net.INetworkPolicyListener;
72import android.net.INetworkPolicyManager;
73import android.net.INetworkStatsService;
74import android.net.LinkAddress;
75import android.net.LinkProperties;
76import android.net.LinkProperties.CompareResult;
77import android.net.LinkQualityInfo;
78import android.net.MobileDataStateTracker;
79import android.net.Network;
80import android.net.NetworkAgent;
81import android.net.NetworkCapabilities;
82import android.net.NetworkConfig;
83import android.net.NetworkInfo;
84import android.net.NetworkInfo.DetailedState;
85import android.net.NetworkQuotaInfo;
86import android.net.NetworkRequest;
87import android.net.NetworkState;
88import android.net.NetworkStateTracker;
89import android.net.NetworkUtils;
90import android.net.Proxy;
91import android.net.ProxyDataTracker;
92import android.net.ProxyInfo;
93import android.net.RouteInfo;
94import android.net.SamplingDataTracker;
95import android.net.Uri;
96import android.net.wimax.WimaxManagerConstants;
97import android.os.AsyncTask;
98import android.os.Binder;
99import android.os.Build;
100import android.os.FileUtils;
101import android.os.Handler;
102import android.os.HandlerThread;
103import android.os.IBinder;
104import android.os.INetworkManagementService;
105import android.os.Looper;
106import android.os.Message;
107import android.os.Messenger;
108import android.os.ParcelFileDescriptor;
109import android.os.PowerManager;
110import android.os.Process;
111import android.os.RemoteException;
112import android.os.ServiceManager;
113import android.os.SystemClock;
114import android.os.SystemProperties;
115import android.os.UserHandle;
116import android.provider.Settings;
117import android.security.Credentials;
118import android.security.KeyStore;
119import android.telephony.TelephonyManager;
120import android.text.TextUtils;
121import android.util.Slog;
122import android.util.SparseArray;
123import android.util.SparseIntArray;
124import android.util.Xml;
125
126import com.android.internal.R;
127import com.android.internal.annotations.GuardedBy;
128import com.android.internal.net.LegacyVpnInfo;
129import com.android.internal.net.VpnConfig;
130import com.android.internal.net.VpnProfile;
131import com.android.internal.telephony.DctConstants;
132import com.android.internal.telephony.Phone;
133import com.android.internal.telephony.PhoneConstants;
134import com.android.internal.telephony.TelephonyIntents;
135import com.android.internal.util.AsyncChannel;
136import com.android.internal.util.IndentingPrintWriter;
137import com.android.internal.util.XmlUtils;
138import com.android.server.am.BatteryStatsService;
139import com.android.server.connectivity.DataConnectionStats;
140import com.android.server.connectivity.Nat464Xlat;
141import com.android.server.connectivity.NetworkAgentInfo;
142import com.android.server.connectivity.NetworkMonitor;
143import com.android.server.connectivity.PacManager;
144import com.android.server.connectivity.Tethering;
145import com.android.server.connectivity.Vpn;
146import com.android.server.net.BaseNetworkObserver;
147import com.android.server.net.LockdownVpnTracker;
148import com.google.android.collect.Lists;
149import com.google.android.collect.Sets;
150
151import dalvik.system.DexClassLoader;
152
153import org.xmlpull.v1.XmlPullParser;
154import org.xmlpull.v1.XmlPullParserException;
155
156import java.io.File;
157import java.io.FileDescriptor;
158import java.io.FileNotFoundException;
159import java.io.FileReader;
160import java.io.IOException;
161import java.io.PrintWriter;
162import java.lang.reflect.Constructor;
163import java.net.HttpURLConnection;
164import java.net.Inet4Address;
165import java.net.Inet6Address;
166import java.net.InetAddress;
167import java.net.URL;
168import java.net.UnknownHostException;
169import java.util.ArrayList;
170import java.util.Arrays;
171import java.util.Collection;
172import java.util.GregorianCalendar;
173import java.util.HashMap;
174import java.util.HashSet;
175import java.util.List;
176import java.util.Map;
177import java.util.Random;
178import java.util.concurrent.atomic.AtomicBoolean;
179import java.util.concurrent.atomic.AtomicInteger;
180
181import javax.net.ssl.HostnameVerifier;
182import javax.net.ssl.HttpsURLConnection;
183import javax.net.ssl.SSLSession;
184
185import static android.net.ConnectivityManager.INVALID_NET_ID;
186
187/**
188 * @hide
189 */
190public class ConnectivityService extends IConnectivityManager.Stub {
191    private static final String TAG = "ConnectivityService";
192
193    private static final boolean DBG = true;
194    private static final boolean VDBG = true; // STOPSHIP
195
196    private static final boolean LOGD_RULES = false;
197
198    // TODO: create better separation between radio types and network types
199
200    // how long to wait before switching back to a radio's default network
201    private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
202    // system property that can override the above value
203    private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
204            "android.telephony.apn-restore";
205
206    // Default value if FAIL_FAST_TIME_MS is not set
207    private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
208    // system property that can override DEFAULT_FAIL_FAST_TIME_MS
209    private static final String FAIL_FAST_TIME_MS =
210            "persist.radio.fail_fast_time_ms";
211
212    private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
213            "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
214
215    private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
216
217    private PendingIntent mSampleIntervalElapsedIntent;
218
219    // Set network sampling interval at 12 minutes, this way, even if the timers get
220    // aggregated, it will fire at around 15 minutes, which should allow us to
221    // aggregate this timer with other timers (specially the socket keep alive timers)
222    private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
223
224    // start network sampling a minute after booting ...
225    private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
226
227    AlarmManager mAlarmManager;
228
229    // used in recursive route setting to add gateways for the host for which
230    // a host route was requested.
231    private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
232
233    private Tethering mTethering;
234
235    private KeyStore mKeyStore;
236
237    @GuardedBy("mVpns")
238    private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
239    private VpnCallback mVpnCallback = new VpnCallback();
240
241    private boolean mLockdownEnabled;
242    private LockdownVpnTracker mLockdownTracker;
243
244    private Nat464Xlat mClat;
245
246    /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
247    private Object mRulesLock = new Object();
248    /** Currently active network rules by UID. */
249    private SparseIntArray mUidRules = new SparseIntArray();
250    /** Set of ifaces that are costly. */
251    private HashSet<String> mMeteredIfaces = Sets.newHashSet();
252
253    /**
254     * Sometimes we want to refer to the individual network state
255     * trackers separately, and sometimes we just want to treat them
256     * abstractly.
257     */
258    private NetworkStateTracker mNetTrackers[];
259
260    /**
261     * Holds references to all NetworkAgentInfos claiming to support the legacy
262     * NetworkType.  We used to have a static set of of NetworkStateTrackers
263     * for each network type.  This is the new model.
264     * Supports synchronous inspection of state.
265     * These are built out at startup such that an unsupported network
266     * doesn't get an ArrayList instance, making this a tristate:
267     * unsupported, supported but not active and active.
268     */
269    private ArrayList<NetworkAgentInfo> mNetworkAgentInfoForType[];
270
271    /* Handles captive portal check on a network */
272    private CaptivePortalTracker mCaptivePortalTracker;
273
274    /**
275     * The link properties that define the current links
276     */
277    private LinkProperties mCurrentLinkProperties[];
278
279    /**
280     * A per Net list of the PID's that requested access to the net
281     * used both as a refcount and for per-PID DNS selection
282     */
283    private List<Integer> mNetRequestersPids[];
284
285    // priority order of the nettrackers
286    // (excluding dynamically set mNetworkPreference)
287    // TODO - move mNetworkTypePreference into this
288    private int[] mPriorityList;
289
290    private Context mContext;
291    private int mNetworkPreference;
292    private int mActiveDefaultNetwork = -1;
293    // 0 is full bad, 100 is full good
294    private int mDefaultInetCondition = 0;
295    private int mDefaultInetConditionPublished = 0;
296    private boolean mInetConditionChangeInFlight = false;
297    private int mDefaultConnectionSequence = 0;
298
299    private Object mDnsLock = new Object();
300    private int mNumDnsEntries;
301
302    private boolean mTestMode;
303    private static ConnectivityService sServiceInstance;
304
305    private INetworkManagementService mNetd;
306    private INetworkPolicyManager mPolicyManager;
307
308    private static final int ENABLED  = 1;
309    private static final int DISABLED = 0;
310
311    private static final boolean ADD = true;
312    private static final boolean REMOVE = false;
313
314    private static final boolean TO_DEFAULT_TABLE = true;
315    private static final boolean TO_SECONDARY_TABLE = false;
316
317    private static final boolean EXEMPT = true;
318    private static final boolean UNEXEMPT = false;
319
320    /**
321     * used internally as a delayed event to make us switch back to the
322     * default network
323     */
324    private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
325
326    /**
327     * used internally to change our mobile data enabled flag
328     */
329    private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
330
331    /**
332     * used internally to synchronize inet condition reports
333     * arg1 = networkType
334     * arg2 = condition (0 bad, 100 good)
335     */
336    private static final int EVENT_INET_CONDITION_CHANGE = 4;
337
338    /**
339     * used internally to mark the end of inet condition hold periods
340     * arg1 = networkType
341     */
342    private static final int EVENT_INET_CONDITION_HOLD_END = 5;
343
344    /**
345     * used internally to set enable/disable cellular data
346     * arg1 = ENBALED or DISABLED
347     */
348    private static final int EVENT_SET_MOBILE_DATA = 7;
349
350    /**
351     * used internally to clear a wakelock when transitioning
352     * from one net to another
353     */
354    private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
355
356    /**
357     * used internally to reload global proxy settings
358     */
359    private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
360
361    /**
362     * used internally to set external dependency met/unmet
363     * arg1 = ENABLED (met) or DISABLED (unmet)
364     * arg2 = NetworkType
365     */
366    private static final int EVENT_SET_DEPENDENCY_MET = 10;
367
368    /**
369     * used internally to send a sticky broadcast delayed.
370     */
371    private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
372
373    /**
374     * Used internally to
375     * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
376     */
377    private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
378
379    private static final int EVENT_VPN_STATE_CHANGED = 13;
380
381    /**
382     * Used internally to disable fail fast of mobile data
383     */
384    private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
385
386    /**
387     * used internally to indicate that data sampling interval is up
388     */
389    private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
390
391    /**
392     * PAC manager has received new port.
393     */
394    private static final int EVENT_PROXY_HAS_CHANGED = 16;
395
396    /**
397     * used internally when registering NetworkFactories
398     * obj = Messenger
399     */
400    private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
401
402    /**
403     * used internally when registering NetworkAgents
404     * obj = Messenger
405     */
406    private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
407
408    /**
409     * used to add a network request
410     * includes a NetworkRequestInfo
411     */
412    private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
413
414    /**
415     * indicates a timeout period is over - check if we had a network yet or not
416     * and if not, call the timeout calback (but leave the request live until they
417     * cancel it.
418     * includes a NetworkRequestInfo
419     */
420    private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
421
422    /**
423     * used to add a network listener - no request
424     * includes a NetworkRequestInfo
425     */
426    private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
427
428    /**
429     * used to remove a network request, either a listener or a real request
430     * includes a NetworkRequest
431     */
432    private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
433
434    /** Handler used for internal events. */
435    final private InternalHandler mHandler;
436    /** Handler used for incoming {@link NetworkStateTracker} events. */
437    final private NetworkStateTrackerHandler mTrackerHandler;
438
439    // list of DeathRecipients used to make sure features are turned off when
440    // a process dies
441    private List<FeatureUser> mFeatureUsers;
442
443    private boolean mSystemReady;
444    private Intent mInitialBroadcast;
445
446    private PowerManager.WakeLock mNetTransitionWakeLock;
447    private String mNetTransitionWakeLockCausedBy = "";
448    private int mNetTransitionWakeLockSerialNumber;
449    private int mNetTransitionWakeLockTimeout;
450
451    private InetAddress mDefaultDns;
452
453    // Lock for protecting access to mAddedRoutes and mExemptAddresses
454    private final Object mRoutesLock = new Object();
455
456    // this collection is used to refcount the added routes - if there are none left
457    // it's time to remove the route from the route table
458    @GuardedBy("mRoutesLock")
459    private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
460
461    // this collection corresponds to the entries of mAddedRoutes that have routing exemptions
462    // used to handle cleanup of exempt rules
463    @GuardedBy("mRoutesLock")
464    private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
465
466    // used in DBG mode to track inet condition reports
467    private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
468    private ArrayList mInetLog;
469
470    // track the current default http proxy - tell the world if we get a new one (real change)
471    private ProxyInfo mDefaultProxy = null;
472    private Object mProxyLock = new Object();
473    private boolean mDefaultProxyDisabled = false;
474
475    // track the global proxy.
476    private ProxyInfo mGlobalProxy = null;
477
478    private PacManager mPacManager = null;
479
480    private SettingsObserver mSettingsObserver;
481
482    private AppOpsManager mAppOpsManager;
483
484    NetworkConfig[] mNetConfigs;
485    int mNetworksDefined;
486
487    private static class RadioAttributes {
488        public int mSimultaneity;
489        public int mType;
490        public RadioAttributes(String init) {
491            String fragments[] = init.split(",");
492            mType = Integer.parseInt(fragments[0]);
493            mSimultaneity = Integer.parseInt(fragments[1]);
494        }
495    }
496    RadioAttributes[] mRadioAttributes;
497
498    // the set of network types that can only be enabled by system/sig apps
499    List mProtectedNetworks;
500
501    private DataConnectionStats mDataConnectionStats;
502
503    private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
504
505    TelephonyManager mTelephonyManager;
506
507    private final static int MIN_NET_ID = 10; // some reserved marks
508    private final static int MAX_NET_ID = 65535;
509    private int mNextNetId = MIN_NET_ID;
510
511    public ConnectivityService(Context context, INetworkManagementService netd,
512            INetworkStatsService statsService, INetworkPolicyManager policyManager) {
513        // Currently, omitting a NetworkFactory will create one internally
514        // TODO: create here when we have cleaner WiMAX support
515        this(context, netd, statsService, policyManager, null);
516    }
517
518    public ConnectivityService(Context context, INetworkManagementService netManager,
519            INetworkStatsService statsService, INetworkPolicyManager policyManager,
520            NetworkFactory netFactory) {
521        if (DBG) log("ConnectivityService starting up");
522
523        NetworkCapabilities netCap = new NetworkCapabilities();
524        netCap.addNetworkCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
525        netCap.addNetworkCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
526        mDefaultRequest = new NetworkRequest(netCap, true);
527        NetworkRequestInfo nri = new NetworkRequestInfo(null, mDefaultRequest, new Binder(),
528                NetworkRequestInfo.REQUEST);
529        mNetworkRequests.put(mDefaultRequest, nri);
530
531        HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
532        handlerThread.start();
533        mHandler = new InternalHandler(handlerThread.getLooper());
534        mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
535
536        if (netFactory == null) {
537            netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
538        }
539
540        // setup our unique device name
541        if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
542            String id = Settings.Secure.getString(context.getContentResolver(),
543                    Settings.Secure.ANDROID_ID);
544            if (id != null && id.length() > 0) {
545                String name = new String("android-").concat(id);
546                SystemProperties.set("net.hostname", name);
547            }
548        }
549
550        // read our default dns server ip
551        String dns = Settings.Global.getString(context.getContentResolver(),
552                Settings.Global.DEFAULT_DNS_SERVER);
553        if (dns == null || dns.length() == 0) {
554            dns = context.getResources().getString(
555                    com.android.internal.R.string.config_default_dns_server);
556        }
557        try {
558            mDefaultDns = NetworkUtils.numericToInetAddress(dns);
559        } catch (IllegalArgumentException e) {
560            loge("Error setting defaultDns using " + dns);
561        }
562
563        mContext = checkNotNull(context, "missing Context");
564        mNetd = checkNotNull(netManager, "missing INetworkManagementService");
565        mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
566        mKeyStore = KeyStore.getInstance();
567        mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
568
569        try {
570            mPolicyManager.registerListener(mPolicyListener);
571        } catch (RemoteException e) {
572            // ouch, no rules updates means some processes may never get network
573            loge("unable to register INetworkPolicyListener" + e.toString());
574        }
575
576        final PowerManager powerManager = (PowerManager) context.getSystemService(
577                Context.POWER_SERVICE);
578        mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
579        mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
580                com.android.internal.R.integer.config_networkTransitionTimeout);
581
582        mNetworkAgentInfoForType = (ArrayList<NetworkAgentInfo>[])
583                new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
584
585        mNetTrackers = new NetworkStateTracker[
586                ConnectivityManager.MAX_NETWORK_TYPE+1];
587        mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
588
589        mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
590        mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
591
592        // Load device network attributes from resources
593        String[] raStrings = context.getResources().getStringArray(
594                com.android.internal.R.array.radioAttributes);
595        for (String raString : raStrings) {
596            RadioAttributes r = new RadioAttributes(raString);
597            if (VDBG) log("raString=" + raString + " r=" + r);
598            if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
599                loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
600                continue;
601            }
602            if (mRadioAttributes[r.mType] != null) {
603                loge("Error in radioAttributes - ignoring attempt to redefine type " +
604                        r.mType);
605                continue;
606            }
607            mRadioAttributes[r.mType] = r;
608        }
609
610        // TODO: What is the "correct" way to do determine if this is a wifi only device?
611        boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
612        log("wifiOnly=" + wifiOnly);
613        String[] naStrings = context.getResources().getStringArray(
614                com.android.internal.R.array.networkAttributes);
615        for (String naString : naStrings) {
616            try {
617                NetworkConfig n = new NetworkConfig(naString);
618                if (VDBG) log("naString=" + naString + " config=" + n);
619                if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
620                    loge("Error in networkAttributes - ignoring attempt to define type " +
621                            n.type);
622                    continue;
623                }
624                if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
625                    log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
626                            n.type);
627                    continue;
628                }
629                if (mNetConfigs[n.type] != null) {
630                    loge("Error in networkAttributes - ignoring attempt to redefine type " +
631                            n.type);
632                    continue;
633                }
634                if (mRadioAttributes[n.radio] == null) {
635                    loge("Error in networkAttributes - ignoring attempt to use undefined " +
636                            "radio " + n.radio + " in network type " + n.type);
637                    continue;
638                }
639                mNetworkAgentInfoForType[n.type] = new ArrayList<NetworkAgentInfo>();
640
641                mNetConfigs[n.type] = n;
642                mNetworksDefined++;
643            } catch(Exception e) {
644                // ignore it - leave the entry null
645            }
646        }
647        if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
648
649        mProtectedNetworks = new ArrayList<Integer>();
650        int[] protectedNetworks = context.getResources().getIntArray(
651                com.android.internal.R.array.config_protectedNetworks);
652        for (int p : protectedNetworks) {
653            if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
654                mProtectedNetworks.add(p);
655            } else {
656                if (DBG) loge("Ignoring protectedNetwork " + p);
657            }
658        }
659
660        // high priority first
661        mPriorityList = new int[mNetworksDefined];
662        {
663            int insertionPoint = mNetworksDefined-1;
664            int currentLowest = 0;
665            int nextLowest = 0;
666            while (insertionPoint > -1) {
667                for (NetworkConfig na : mNetConfigs) {
668                    if (na == null) continue;
669                    if (na.priority < currentLowest) continue;
670                    if (na.priority > currentLowest) {
671                        if (na.priority < nextLowest || nextLowest == 0) {
672                            nextLowest = na.priority;
673                        }
674                        continue;
675                    }
676                    mPriorityList[insertionPoint--] = na.type;
677                }
678                currentLowest = nextLowest;
679                nextLowest = 0;
680            }
681        }
682
683        mNetRequestersPids =
684                (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
685        for (int i : mPriorityList) {
686            mNetRequestersPids[i] = new ArrayList<Integer>();
687        }
688
689        mFeatureUsers = new ArrayList<FeatureUser>();
690
691        mTestMode = SystemProperties.get("cm.test.mode").equals("true")
692                && SystemProperties.get("ro.build.type").equals("eng");
693
694        // Create and start trackers for hard-coded networks
695        for (int targetNetworkType : mPriorityList) {
696            final NetworkConfig config = mNetConfigs[targetNetworkType];
697            final NetworkStateTracker tracker;
698            try {
699                tracker = netFactory.createTracker(targetNetworkType, config);
700                mNetTrackers[targetNetworkType] = tracker;
701            } catch (IllegalArgumentException e) {
702                Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
703                        + " tracker: " + e);
704                continue;
705            }
706
707            tracker.startMonitoring(context, mTrackerHandler);
708            if (config.isDefault()) {
709                tracker.reconnect();
710            }
711        }
712
713        mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
714
715        //set up the listener for user state for creating user VPNs
716        IntentFilter intentFilter = new IntentFilter();
717        intentFilter.addAction(Intent.ACTION_USER_STARTING);
718        intentFilter.addAction(Intent.ACTION_USER_STOPPING);
719        mContext.registerReceiverAsUser(
720                mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
721        mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
722
723        try {
724            mNetd.registerObserver(mTethering);
725            mNetd.registerObserver(mDataActivityObserver);
726            mNetd.registerObserver(mClat);
727        } catch (RemoteException e) {
728            loge("Error registering observer :" + e);
729        }
730
731        if (DBG) {
732            mInetLog = new ArrayList();
733        }
734
735        mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
736        mSettingsObserver.observe(mContext);
737
738        mDataConnectionStats = new DataConnectionStats(mContext);
739        mDataConnectionStats.startMonitoring();
740
741        // start network sampling ..
742        Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
743        mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
744                SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
745
746        mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
747        setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
748
749        IntentFilter filter = new IntentFilter();
750        filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
751        mContext.registerReceiver(
752                new BroadcastReceiver() {
753                    @Override
754                    public void onReceive(Context context, Intent intent) {
755                        String action = intent.getAction();
756                        if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
757                            mHandler.sendMessage(mHandler.obtainMessage
758                                    (EVENT_SAMPLE_INTERVAL_ELAPSED));
759                        }
760                    }
761                },
762                new IntentFilter(filter));
763
764        mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
765
766        filter = new IntentFilter();
767        filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
768        mContext.registerReceiver(mProvisioningReceiver, filter);
769
770        mAppOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
771    }
772
773    private synchronized int nextNetId() {
774        int netId = mNextNetId;
775        if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
776        return netId;
777    }
778
779    /**
780     * Factory that creates {@link NetworkStateTracker} instances using given
781     * {@link NetworkConfig}.
782     *
783     * TODO - this is obsolete and will be deleted.  It's replaced by the
784     * registerNetworkFactory call and protocol.
785     * @Deprecated in favor of registerNetworkFactory dynamic bindings
786     */
787    public interface NetworkFactory {
788        public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
789    }
790
791    private static class DefaultNetworkFactory implements NetworkFactory {
792        private final Context mContext;
793        private final Handler mTrackerHandler;
794
795        public DefaultNetworkFactory(Context context, Handler trackerHandler) {
796            mContext = context;
797            mTrackerHandler = trackerHandler;
798        }
799
800        @Override
801        public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
802            switch (config.radio) {
803                case TYPE_DUMMY:
804                    return new DummyDataStateTracker(targetNetworkType, config.name);
805                case TYPE_BLUETOOTH:
806                    return BluetoothTetheringDataTracker.getInstance();
807                case TYPE_WIMAX:
808                    return makeWimaxStateTracker(mContext, mTrackerHandler);
809                case TYPE_ETHERNET:
810                    return EthernetDataTracker.getInstance();
811                case TYPE_PROXY:
812                    return new ProxyDataTracker();
813                default:
814                    throw new IllegalArgumentException(
815                            "Trying to create a NetworkStateTracker for an unknown radio type: "
816                            + config.radio);
817            }
818        }
819    }
820
821    /**
822     * Loads external WiMAX library and registers as system service, returning a
823     * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
824     * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
825     */
826    private static NetworkStateTracker makeWimaxStateTracker(
827            Context context, Handler trackerHandler) {
828        // Initialize Wimax
829        DexClassLoader wimaxClassLoader;
830        Class wimaxStateTrackerClass = null;
831        Class wimaxServiceClass = null;
832        Class wimaxManagerClass;
833        String wimaxJarLocation;
834        String wimaxLibLocation;
835        String wimaxManagerClassName;
836        String wimaxServiceClassName;
837        String wimaxStateTrackerClassName;
838
839        NetworkStateTracker wimaxStateTracker = null;
840
841        boolean isWimaxEnabled = context.getResources().getBoolean(
842                com.android.internal.R.bool.config_wimaxEnabled);
843
844        if (isWimaxEnabled) {
845            try {
846                wimaxJarLocation = context.getResources().getString(
847                        com.android.internal.R.string.config_wimaxServiceJarLocation);
848                wimaxLibLocation = context.getResources().getString(
849                        com.android.internal.R.string.config_wimaxNativeLibLocation);
850                wimaxManagerClassName = context.getResources().getString(
851                        com.android.internal.R.string.config_wimaxManagerClassname);
852                wimaxServiceClassName = context.getResources().getString(
853                        com.android.internal.R.string.config_wimaxServiceClassname);
854                wimaxStateTrackerClassName = context.getResources().getString(
855                        com.android.internal.R.string.config_wimaxStateTrackerClassname);
856
857                if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
858                wimaxClassLoader =  new DexClassLoader(wimaxJarLocation,
859                        new ContextWrapper(context).getCacheDir().getAbsolutePath(),
860                        wimaxLibLocation, ClassLoader.getSystemClassLoader());
861
862                try {
863                    wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
864                    wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
865                    wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
866                } catch (ClassNotFoundException ex) {
867                    loge("Exception finding Wimax classes: " + ex.toString());
868                    return null;
869                }
870            } catch(Resources.NotFoundException ex) {
871                loge("Wimax Resources does not exist!!! ");
872                return null;
873            }
874
875            try {
876                if (DBG) log("Starting Wimax Service... ");
877
878                Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
879                        (new Class[] {Context.class, Handler.class});
880                wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
881                        context, trackerHandler);
882
883                Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
884                        (new Class[] {Context.class, wimaxStateTrackerClass});
885                wmxSrvConst.setAccessible(true);
886                IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
887                wmxSrvConst.setAccessible(false);
888
889                ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
890
891            } catch(Exception ex) {
892                loge("Exception creating Wimax classes: " + ex.toString());
893                return null;
894            }
895        } else {
896            loge("Wimax is not enabled or not added to the network attributes!!! ");
897            return null;
898        }
899
900        return wimaxStateTracker;
901    }
902
903    private int getConnectivityChangeDelay() {
904        final ContentResolver cr = mContext.getContentResolver();
905
906        /** Check system properties for the default value then use secure settings value, if any. */
907        int defaultDelay = SystemProperties.getInt(
908                "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
909                ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
910        return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
911                defaultDelay);
912    }
913
914    private boolean teardown(NetworkStateTracker netTracker) {
915        if (netTracker.teardown()) {
916            netTracker.setTeardownRequested(true);
917            return true;
918        } else {
919            return false;
920        }
921    }
922
923    /**
924     * Check if UID should be blocked from using the network represented by the
925     * given {@link NetworkStateTracker}.
926     */
927    private boolean isNetworkBlocked(int networkType, int uid) {
928        final boolean networkCostly;
929        final int uidRules;
930
931        LinkProperties lp = getLinkPropertiesForType(networkType);
932        final String iface = (lp == null ? "" : lp.getInterfaceName());
933        synchronized (mRulesLock) {
934            networkCostly = mMeteredIfaces.contains(iface);
935            uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
936        }
937
938        if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
939            return true;
940        }
941
942        // no restrictive rules; network is visible
943        return false;
944    }
945
946    /**
947     * Return a filtered {@link NetworkInfo}, potentially marked
948     * {@link DetailedState#BLOCKED} based on
949     * {@link #isNetworkBlocked}.
950     */
951    private NetworkInfo getFilteredNetworkInfo(int networkType, int uid) {
952        NetworkInfo info = getNetworkInfoForType(networkType);
953        if (isNetworkBlocked(networkType, uid)) {
954            // network is blocked; clone and override state
955            info = new NetworkInfo(info);
956            info.setDetailedState(DetailedState.BLOCKED, null, null);
957        }
958        if (mLockdownTracker != null) {
959            info = mLockdownTracker.augmentNetworkInfo(info);
960        }
961        return info;
962    }
963
964    /**
965     * Return NetworkInfo for the active (i.e., connected) network interface.
966     * It is assumed that at most one network is active at a time. If more
967     * than one is active, it is indeterminate which will be returned.
968     * @return the info for the active network, or {@code null} if none is
969     * active
970     */
971    @Override
972    public NetworkInfo getActiveNetworkInfo() {
973        enforceAccessPermission();
974        final int uid = Binder.getCallingUid();
975        return getNetworkInfo(mActiveDefaultNetwork, uid);
976    }
977
978    // only called when the default request is satisfied
979    private void updateActiveDefaultNetwork(NetworkAgentInfo nai) {
980        if (nai != null) {
981            mActiveDefaultNetwork = nai.networkInfo.getType();
982        } else {
983            mActiveDefaultNetwork = TYPE_NONE;
984        }
985    }
986
987    /**
988     * Find the first Provisioning network.
989     *
990     * @return NetworkInfo or null if none.
991     */
992    private NetworkInfo getProvisioningNetworkInfo() {
993        enforceAccessPermission();
994
995        // Find the first Provisioning Network
996        NetworkInfo provNi = null;
997        for (NetworkInfo ni : getAllNetworkInfo()) {
998            if (ni.isConnectedToProvisioningNetwork()) {
999                provNi = ni;
1000                break;
1001            }
1002        }
1003        if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
1004        return provNi;
1005    }
1006
1007    /**
1008     * Find the first Provisioning network or the ActiveDefaultNetwork
1009     * if there is no Provisioning network
1010     *
1011     * @return NetworkInfo or null if none.
1012     */
1013    @Override
1014    public NetworkInfo getProvisioningOrActiveNetworkInfo() {
1015        enforceAccessPermission();
1016
1017        NetworkInfo provNi = getProvisioningNetworkInfo();
1018        if (provNi == null) {
1019            final int uid = Binder.getCallingUid();
1020            provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
1021        }
1022        if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
1023        return provNi;
1024    }
1025
1026    public NetworkInfo getActiveNetworkInfoUnfiltered() {
1027        enforceAccessPermission();
1028        if (isNetworkTypeValid(mActiveDefaultNetwork)) {
1029            return getNetworkInfoForType(mActiveDefaultNetwork);
1030        }
1031        return null;
1032    }
1033
1034    @Override
1035    public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1036        enforceConnectivityInternalPermission();
1037        return getNetworkInfo(mActiveDefaultNetwork, uid);
1038    }
1039
1040    @Override
1041    public NetworkInfo getNetworkInfo(int networkType) {
1042        enforceAccessPermission();
1043        final int uid = Binder.getCallingUid();
1044        return getNetworkInfo(networkType, uid);
1045    }
1046
1047    private NetworkInfo getNetworkInfo(int networkType, int uid) {
1048        NetworkInfo info = null;
1049        if (isNetworkTypeValid(networkType)) {
1050            if (getNetworkInfoForType(networkType) != null) {
1051                info = getFilteredNetworkInfo(networkType, uid);
1052            }
1053        }
1054        return info;
1055    }
1056
1057    @Override
1058    public NetworkInfo[] getAllNetworkInfo() {
1059        enforceAccessPermission();
1060        final int uid = Binder.getCallingUid();
1061        final ArrayList<NetworkInfo> result = Lists.newArrayList();
1062        synchronized (mRulesLock) {
1063            for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1064                    networkType++) {
1065                if (getNetworkInfoForType(networkType) != null) {
1066                    result.add(getFilteredNetworkInfo(networkType, uid));
1067                }
1068            }
1069        }
1070        return result.toArray(new NetworkInfo[result.size()]);
1071    }
1072
1073    @Override
1074    public boolean isNetworkSupported(int networkType) {
1075        enforceAccessPermission();
1076        return (isNetworkTypeValid(networkType) && (getNetworkInfoForType(networkType) != null));
1077    }
1078
1079    /**
1080     * Return LinkProperties for the active (i.e., connected) default
1081     * network interface.  It is assumed that at most one default network
1082     * is active at a time. If more than one is active, it is indeterminate
1083     * which will be returned.
1084     * @return the ip properties for the active network, or {@code null} if
1085     * none is active
1086     */
1087    @Override
1088    public LinkProperties getActiveLinkProperties() {
1089        return getLinkPropertiesForType(mActiveDefaultNetwork);
1090    }
1091
1092    @Override
1093    public LinkProperties getLinkPropertiesForType(int networkType) {
1094        enforceAccessPermission();
1095        if (isNetworkTypeValid(networkType)) {
1096            return getLinkPropertiesForTypeInternal(networkType);
1097        }
1098        return null;
1099    }
1100
1101    // TODO - this should be ALL networks
1102    @Override
1103    public LinkProperties getLinkProperties(Network network) {
1104        enforceAccessPermission();
1105        NetworkAgentInfo nai = mNetworkForNetId.get(network.netId);
1106        if (nai != null) return new LinkProperties(nai.linkProperties);
1107        return null;
1108    }
1109
1110    @Override
1111    public NetworkCapabilities getNetworkCapabilities(Network network) {
1112        enforceAccessPermission();
1113        NetworkAgentInfo nai = mNetworkForNetId.get(network.netId);
1114        if (nai != null) return new NetworkCapabilities(nai.networkCapabilities);
1115        return null;
1116    }
1117
1118    @Override
1119    public NetworkState[] getAllNetworkState() {
1120        enforceAccessPermission();
1121        final int uid = Binder.getCallingUid();
1122        final ArrayList<NetworkState> result = Lists.newArrayList();
1123        synchronized (mRulesLock) {
1124            for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1125                    networkType++) {
1126                if (getNetworkInfoForType(networkType) != null) {
1127                    final NetworkInfo info = getFilteredNetworkInfo(networkType, uid);
1128                    final LinkProperties lp = getLinkPropertiesForTypeInternal(networkType);
1129                    final NetworkCapabilities netcap = getNetworkCapabilitiesForType(networkType);
1130                    result.add(new NetworkState(info, lp, netcap));
1131                }
1132            }
1133        }
1134        return result.toArray(new NetworkState[result.size()]);
1135    }
1136
1137    private NetworkState getNetworkStateUnchecked(int networkType) {
1138        if (isNetworkTypeValid(networkType)) {
1139            NetworkInfo info = getNetworkInfoForType(networkType);
1140            if (info != null) {
1141                return new NetworkState(info,
1142                        getLinkPropertiesForTypeInternal(networkType),
1143                        getNetworkCapabilitiesForType(networkType));
1144            }
1145        }
1146        return null;
1147    }
1148
1149    @Override
1150    public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1151        enforceAccessPermission();
1152
1153        final long token = Binder.clearCallingIdentity();
1154        try {
1155            final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1156            if (state != null) {
1157                try {
1158                    return mPolicyManager.getNetworkQuotaInfo(state);
1159                } catch (RemoteException e) {
1160                }
1161            }
1162            return null;
1163        } finally {
1164            Binder.restoreCallingIdentity(token);
1165        }
1166    }
1167
1168    @Override
1169    public boolean isActiveNetworkMetered() {
1170        enforceAccessPermission();
1171        final long token = Binder.clearCallingIdentity();
1172        try {
1173            return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
1174        } finally {
1175            Binder.restoreCallingIdentity(token);
1176        }
1177    }
1178
1179    private boolean isNetworkMeteredUnchecked(int networkType) {
1180        final NetworkState state = getNetworkStateUnchecked(networkType);
1181        if (state != null) {
1182            try {
1183                return mPolicyManager.isNetworkMetered(state);
1184            } catch (RemoteException e) {
1185            }
1186        }
1187        return false;
1188    }
1189
1190    private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1191        @Override
1192        public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
1193            int deviceType = Integer.parseInt(label);
1194            sendDataActivityBroadcast(deviceType, active, tsNanos);
1195        }
1196    };
1197
1198    /**
1199     * Used to notice when the calling process dies so we can self-expire
1200     *
1201     * Also used to know if the process has cleaned up after itself when
1202     * our auto-expire timer goes off.  The timer has a link to an object.
1203     *
1204     */
1205    private class FeatureUser implements IBinder.DeathRecipient {
1206        int mNetworkType;
1207        String mFeature;
1208        IBinder mBinder;
1209        int mPid;
1210        int mUid;
1211        long mCreateTime;
1212
1213        FeatureUser(int type, String feature, IBinder binder) {
1214            super();
1215            mNetworkType = type;
1216            mFeature = feature;
1217            mBinder = binder;
1218            mPid = getCallingPid();
1219            mUid = getCallingUid();
1220            mCreateTime = System.currentTimeMillis();
1221
1222            try {
1223                mBinder.linkToDeath(this, 0);
1224            } catch (RemoteException e) {
1225                binderDied();
1226            }
1227        }
1228
1229        void unlinkDeathRecipient() {
1230            mBinder.unlinkToDeath(this, 0);
1231        }
1232
1233        public void binderDied() {
1234            log("ConnectivityService FeatureUser binderDied(" +
1235                    mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1236                    (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1237            stopUsingNetworkFeature(this, false);
1238        }
1239
1240        public void expire() {
1241            if (VDBG) {
1242                log("ConnectivityService FeatureUser expire(" +
1243                        mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1244                        (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1245            }
1246            stopUsingNetworkFeature(this, false);
1247        }
1248
1249        public boolean isSameUser(FeatureUser u) {
1250            if (u == null) return false;
1251
1252            return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1253        }
1254
1255        public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1256            if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1257                TextUtils.equals(mFeature, feature)) {
1258                return true;
1259            }
1260            return false;
1261        }
1262
1263        public String toString() {
1264            return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1265                    (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1266        }
1267    }
1268
1269    // javadoc from interface
1270    public int startUsingNetworkFeature(int networkType, String feature,
1271            IBinder binder) {
1272        long startTime = 0;
1273        if (DBG) {
1274            startTime = SystemClock.elapsedRealtime();
1275        }
1276        if (VDBG) {
1277            log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1278                    + Binder.getCallingUid());
1279        }
1280        enforceChangePermission();
1281        try {
1282            if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1283                    mNetConfigs[networkType] == null) {
1284                return PhoneConstants.APN_REQUEST_FAILED;
1285            }
1286
1287            FeatureUser f = new FeatureUser(networkType, feature, binder);
1288
1289            // TODO - move this into individual networktrackers
1290            int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1291
1292            if (mLockdownEnabled) {
1293                // Since carrier APNs usually aren't available from VPN
1294                // endpoint, mark them as unavailable.
1295                return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1296            }
1297
1298            if (mProtectedNetworks.contains(usedNetworkType)) {
1299                enforceConnectivityInternalPermission();
1300            }
1301
1302            // if UID is restricted, don't allow them to bring up metered APNs
1303            final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1304            final int uidRules;
1305            synchronized (mRulesLock) {
1306                uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1307            }
1308            if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
1309                return PhoneConstants.APN_REQUEST_FAILED;
1310            }
1311
1312            NetworkStateTracker network = mNetTrackers[usedNetworkType];
1313            if (network != null) {
1314                Integer currentPid = new Integer(getCallingPid());
1315                if (usedNetworkType != networkType) {
1316                    NetworkInfo ni = network.getNetworkInfo();
1317
1318                    if (ni.isAvailable() == false) {
1319                        if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1320                            if (DBG) log("special network not available ni=" + ni.getTypeName());
1321                            return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1322                        } else {
1323                            // else make the attempt anyway - probably giving REQUEST_STARTED below
1324                            if (DBG) {
1325                                log("special network not available, but try anyway ni=" +
1326                                        ni.getTypeName());
1327                            }
1328                        }
1329                    }
1330
1331                    int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1332
1333                    synchronized(this) {
1334                        boolean addToList = true;
1335                        if (restoreTimer < 0) {
1336                            // In case there is no timer is specified for the feature,
1337                            // make sure we don't add duplicate entry with the same request.
1338                            for (FeatureUser u : mFeatureUsers) {
1339                                if (u.isSameUser(f)) {
1340                                    // Duplicate user is found. Do not add.
1341                                    addToList = false;
1342                                    break;
1343                                }
1344                            }
1345                        }
1346
1347                        if (addToList) mFeatureUsers.add(f);
1348                        if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1349                            // this gets used for per-pid dns when connected
1350                            mNetRequestersPids[usedNetworkType].add(currentPid);
1351                        }
1352                    }
1353
1354                    if (restoreTimer >= 0) {
1355                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
1356                                EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1357                    }
1358
1359                    if ((ni.isConnectedOrConnecting() == true) &&
1360                            !network.isTeardownRequested()) {
1361                        if (ni.isConnected() == true) {
1362                            final long token = Binder.clearCallingIdentity();
1363                            try {
1364                                // add the pid-specific dns
1365                                handleDnsConfigurationChange(usedNetworkType);
1366                                if (VDBG) log("special network already active");
1367                            } finally {
1368                                Binder.restoreCallingIdentity(token);
1369                            }
1370                            return PhoneConstants.APN_ALREADY_ACTIVE;
1371                        }
1372                        if (VDBG) log("special network already connecting");
1373                        return PhoneConstants.APN_REQUEST_STARTED;
1374                    }
1375
1376                    // check if the radio in play can make another contact
1377                    // assume if cannot for now
1378
1379                    if (DBG) {
1380                        log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1381                                feature);
1382                    }
1383                    if (network.reconnect()) {
1384                        if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
1385                        return PhoneConstants.APN_REQUEST_STARTED;
1386                    } else {
1387                        if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
1388                        return PhoneConstants.APN_REQUEST_FAILED;
1389                    }
1390                } else {
1391                    // need to remember this unsupported request so we respond appropriately on stop
1392                    synchronized(this) {
1393                        mFeatureUsers.add(f);
1394                        if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1395                            // this gets used for per-pid dns when connected
1396                            mNetRequestersPids[usedNetworkType].add(currentPid);
1397                        }
1398                    }
1399                    if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
1400                    return -1;
1401                }
1402            }
1403            if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
1404            return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1405         } finally {
1406            if (DBG) {
1407                final long execTime = SystemClock.elapsedRealtime() - startTime;
1408                if (execTime > 250) {
1409                    loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1410                } else {
1411                    if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1412                }
1413            }
1414         }
1415    }
1416
1417    // javadoc from interface
1418    public int stopUsingNetworkFeature(int networkType, String feature) {
1419        enforceChangePermission();
1420
1421        int pid = getCallingPid();
1422        int uid = getCallingUid();
1423
1424        FeatureUser u = null;
1425        boolean found = false;
1426
1427        synchronized(this) {
1428            for (FeatureUser x : mFeatureUsers) {
1429                if (x.isSameUser(pid, uid, networkType, feature)) {
1430                    u = x;
1431                    found = true;
1432                    break;
1433                }
1434            }
1435        }
1436        if (found && u != null) {
1437            if (VDBG) log("stopUsingNetworkFeature: X");
1438            // stop regardless of how many other time this proc had called start
1439            return stopUsingNetworkFeature(u, true);
1440        } else {
1441            // none found!
1442            if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
1443            return 1;
1444        }
1445    }
1446
1447    private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1448        int networkType = u.mNetworkType;
1449        String feature = u.mFeature;
1450        int pid = u.mPid;
1451        int uid = u.mUid;
1452
1453        NetworkStateTracker tracker = null;
1454        boolean callTeardown = false;  // used to carry our decision outside of sync block
1455
1456        if (VDBG) {
1457            log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
1458        }
1459
1460        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1461            if (DBG) {
1462                log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1463                        ", net is invalid");
1464            }
1465            return -1;
1466        }
1467
1468        // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1469        // sync block
1470        synchronized(this) {
1471            // check if this process still has an outstanding start request
1472            if (!mFeatureUsers.contains(u)) {
1473                if (VDBG) {
1474                    log("stopUsingNetworkFeature: this process has no outstanding requests" +
1475                        ", ignoring");
1476                }
1477                return 1;
1478            }
1479            u.unlinkDeathRecipient();
1480            mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1481            // If we care about duplicate requests, check for that here.
1482            //
1483            // This is done to support the extension of a request - the app
1484            // can request we start the network feature again and renew the
1485            // auto-shutoff delay.  Normal "stop" calls from the app though
1486            // do not pay attention to duplicate requests - in effect the
1487            // API does not refcount and a single stop will counter multiple starts.
1488            if (ignoreDups == false) {
1489                for (FeatureUser x : mFeatureUsers) {
1490                    if (x.isSameUser(u)) {
1491                        if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
1492                        return 1;
1493                    }
1494                }
1495            }
1496
1497            // TODO - move to individual network trackers
1498            int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1499
1500            tracker =  mNetTrackers[usedNetworkType];
1501            if (tracker == null) {
1502                if (DBG) {
1503                    log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1504                            " no known tracker for used net type " + usedNetworkType);
1505                }
1506                return -1;
1507            }
1508            if (usedNetworkType != networkType) {
1509                Integer currentPid = new Integer(pid);
1510                mNetRequestersPids[usedNetworkType].remove(currentPid);
1511
1512                final long token = Binder.clearCallingIdentity();
1513                try {
1514                    reassessPidDns(pid, true);
1515                } finally {
1516                    Binder.restoreCallingIdentity(token);
1517                }
1518                flushVmDnsCache();
1519                if (mNetRequestersPids[usedNetworkType].size() != 0) {
1520                    if (VDBG) {
1521                        log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1522                                " others still using it");
1523                    }
1524                    return 1;
1525                }
1526                callTeardown = true;
1527            } else {
1528                if (DBG) {
1529                    log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1530                            " not a known feature - dropping");
1531                }
1532            }
1533        }
1534
1535        if (callTeardown) {
1536            if (DBG) {
1537                log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1538            }
1539            tracker.teardown();
1540            return 1;
1541        } else {
1542            return -1;
1543        }
1544    }
1545
1546    /**
1547     * Check if the address falls into any of currently running VPN's route's.
1548     */
1549    private boolean isAddressUnderVpn(InetAddress address) {
1550        synchronized (mVpns) {
1551            synchronized (mRoutesLock) {
1552                int uid = UserHandle.getCallingUserId();
1553                Vpn vpn = mVpns.get(uid);
1554                if (vpn == null) {
1555                    return false;
1556                }
1557
1558                // Check if an exemption exists for this address.
1559                for (LinkAddress destination : mExemptAddresses) {
1560                    if (!NetworkUtils.addressTypeMatches(address, destination.getAddress())) {
1561                        continue;
1562                    }
1563
1564                    int prefix = destination.getNetworkPrefixLength();
1565                    InetAddress addrMasked = NetworkUtils.getNetworkPart(address, prefix);
1566                    InetAddress destMasked = NetworkUtils.getNetworkPart(destination.getAddress(),
1567                            prefix);
1568
1569                    if (addrMasked.equals(destMasked)) {
1570                        return false;
1571                    }
1572                }
1573
1574                // Finally check if the address is covered by the VPN.
1575                return vpn.isAddressCovered(address);
1576            }
1577        }
1578    }
1579
1580    /**
1581     * @deprecated use requestRouteToHostAddress instead
1582     *
1583     * Ensure that a network route exists to deliver traffic to the specified
1584     * host via the specified network interface.
1585     * @param networkType the type of the network over which traffic to the
1586     * specified host is to be routed
1587     * @param hostAddress the IP address of the host to which the route is
1588     * desired
1589     * @return {@code true} on success, {@code false} on failure
1590     */
1591    public boolean requestRouteToHost(int networkType, int hostAddress, String packageName) {
1592        InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1593
1594        if (inetAddress == null) {
1595            return false;
1596        }
1597
1598        return requestRouteToHostAddress(networkType, inetAddress.getAddress(), packageName);
1599    }
1600
1601    /**
1602     * Ensure that a network route exists to deliver traffic to the specified
1603     * host via the specified network interface.
1604     * @param networkType the type of the network over which traffic to the
1605     * specified host is to be routed
1606     * @param hostAddress the IP address of the host to which the route is
1607     * desired
1608     * @return {@code true} on success, {@code false} on failure
1609     */
1610    public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
1611            String packageName) {
1612        enforceChangePermission();
1613        if (mProtectedNetworks.contains(networkType)) {
1614            enforceConnectivityInternalPermission();
1615        }
1616        boolean exempt;
1617        InetAddress addr;
1618        try {
1619            addr = InetAddress.getByAddress(hostAddress);
1620        } catch (UnknownHostException e) {
1621            if (DBG) log("requestRouteToHostAddress got " + e.toString());
1622            return false;
1623        }
1624        // System apps may request routes bypassing the VPN to keep other networks working.
1625        if (Binder.getCallingUid() == Process.SYSTEM_UID) {
1626            exempt = true;
1627        } else {
1628            mAppOpsManager.checkPackage(Binder.getCallingUid(), packageName);
1629            try {
1630                ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(packageName,
1631                        0);
1632                exempt = (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
1633            } catch (NameNotFoundException e) {
1634                throw new IllegalArgumentException("Failed to find calling package details", e);
1635            }
1636        }
1637
1638        // Non-exempt routeToHost's can only be added if the host is not covered by the VPN.
1639        // This can be either because the VPN's routes do not cover the destination or a
1640        // system application added an exemption that covers this destination.
1641        if (!exempt && isAddressUnderVpn(addr)) {
1642            return false;
1643        }
1644
1645        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1646            if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1647            return false;
1648        }
1649        NetworkStateTracker tracker = mNetTrackers[networkType];
1650        DetailedState netState = DetailedState.DISCONNECTED;
1651        if (tracker != null) {
1652            netState = tracker.getNetworkInfo().getDetailedState();
1653        }
1654
1655        if ((netState != DetailedState.CONNECTED &&
1656                netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
1657                tracker.isTeardownRequested()) {
1658            if (VDBG) {
1659                log("requestRouteToHostAddress on down network "
1660                        + "(" + networkType + ") - dropped"
1661                        + " tracker=" + tracker
1662                        + " netState=" + netState
1663                        + " isTeardownRequested="
1664                            + ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
1665            }
1666            return false;
1667        }
1668        final long token = Binder.clearCallingIdentity();
1669        try {
1670            LinkProperties lp = tracker.getLinkProperties();
1671            boolean ok = addRouteToAddress(lp, addr, exempt, tracker.getNetwork().netId);
1672            if (DBG) log("requestRouteToHostAddress ok=" + ok);
1673            return ok;
1674        } finally {
1675            Binder.restoreCallingIdentity(token);
1676        }
1677    }
1678
1679    private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1680            boolean exempt, int netId) {
1681        return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt, netId);
1682    }
1683
1684    private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable, int netId) {
1685        return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT, netId);
1686    }
1687
1688    private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt,
1689                                      int netId) {
1690        return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt, netId);
1691    }
1692
1693    private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr, int netId) {
1694        return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT, netId);
1695    }
1696
1697    private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1698            boolean toDefaultTable, boolean exempt, int netId) {
1699        RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1700        if (bestRoute == null) {
1701            bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1702        } else {
1703            String iface = bestRoute.getInterface();
1704            if (bestRoute.getGateway().equals(addr)) {
1705                // if there is no better route, add the implied hostroute for our gateway
1706                bestRoute = RouteInfo.makeHostRoute(addr, iface);
1707            } else {
1708                // if we will connect to this through another route, add a direct route
1709                // to it's gateway
1710                bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1711            }
1712        }
1713        return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt, netId);
1714    }
1715
1716    private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1717            boolean toDefaultTable, boolean exempt, int netId) {
1718        if ((lp == null) || (r == null)) {
1719            if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
1720            return false;
1721        }
1722
1723        if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1724            loge("Error modifying route - too much recursion");
1725            return false;
1726        }
1727
1728        String ifaceName = r.getInterface();
1729        if(ifaceName == null) {
1730            loge("Error modifying route - no interface name");
1731            return false;
1732        }
1733        if (r.hasGateway()) {
1734            RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
1735            if (bestRoute != null) {
1736                if (bestRoute.getGateway().equals(r.getGateway())) {
1737                    // if there is no better route, add the implied hostroute for our gateway
1738                    bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
1739                } else {
1740                    // if we will connect to our gateway through another route, add a direct
1741                    // route to it's gateway
1742                    bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1743                                                        bestRoute.getGateway(),
1744                                                        ifaceName);
1745                }
1746                modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt, netId);
1747            }
1748        }
1749        if (doAdd) {
1750            if (VDBG) log("Adding " + r + " for interface " + ifaceName);
1751            try {
1752                if (toDefaultTable) {
1753                    synchronized (mRoutesLock) {
1754                        // only track default table - only one apps can effect
1755                        mAddedRoutes.add(r);
1756                        mNetd.addRoute(netId, r);
1757                        if (exempt) {
1758                            LinkAddress dest = r.getDestination();
1759                            if (!mExemptAddresses.contains(dest)) {
1760                                mNetd.setHostExemption(dest);
1761                                mExemptAddresses.add(dest);
1762                            }
1763                        }
1764                    }
1765                } else {
1766                    mNetd.addRoute(netId, r);
1767                }
1768            } catch (Exception e) {
1769                // never crash - catch them all
1770                if (DBG) loge("Exception trying to add a route: " + e);
1771                return false;
1772            }
1773        } else {
1774            // if we remove this one and there are no more like it, then refcount==0 and
1775            // we can remove it from the table
1776            if (toDefaultTable) {
1777                synchronized (mRoutesLock) {
1778                    mAddedRoutes.remove(r);
1779                    if (mAddedRoutes.contains(r) == false) {
1780                        if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1781                        try {
1782                            mNetd.removeRoute(netId, r);
1783                            LinkAddress dest = r.getDestination();
1784                            if (mExemptAddresses.contains(dest)) {
1785                                mNetd.clearHostExemption(dest);
1786                                mExemptAddresses.remove(dest);
1787                            }
1788                        } catch (Exception e) {
1789                            // never crash - catch them all
1790                            if (VDBG) loge("Exception trying to remove a route: " + e);
1791                            return false;
1792                        }
1793                    } else {
1794                        if (VDBG) log("not removing " + r + " as it's still in use");
1795                    }
1796                }
1797            } else {
1798                if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1799                try {
1800                    mNetd.removeRoute(netId, r);
1801                } catch (Exception e) {
1802                    // never crash - catch them all
1803                    if (VDBG) loge("Exception trying to remove a route: " + e);
1804                    return false;
1805                }
1806            }
1807        }
1808        return true;
1809    }
1810
1811    /**
1812     * @see ConnectivityManager#getMobileDataEnabled()
1813     */
1814    public boolean getMobileDataEnabled() {
1815        // TODO: This detail should probably be in DataConnectionTracker's
1816        //       which is where we store the value and maybe make this
1817        //       asynchronous.
1818        enforceAccessPermission();
1819        boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1820                Settings.Global.MOBILE_DATA, 1) == 1;
1821        if (VDBG) log("getMobileDataEnabled returning " + retVal);
1822        return retVal;
1823    }
1824
1825    public void setDataDependency(int networkType, boolean met) {
1826        enforceConnectivityInternalPermission();
1827
1828        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1829                (met ? ENABLED : DISABLED), networkType));
1830    }
1831
1832    private void handleSetDependencyMet(int networkType, boolean met) {
1833        if (mNetTrackers[networkType] != null) {
1834            if (DBG) {
1835                log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1836            }
1837            mNetTrackers[networkType].setDependencyMet(met);
1838        }
1839    }
1840
1841    private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1842        @Override
1843        public void onUidRulesChanged(int uid, int uidRules) {
1844            // caller is NPMS, since we only register with them
1845            if (LOGD_RULES) {
1846                log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1847            }
1848
1849            synchronized (mRulesLock) {
1850                // skip update when we've already applied rules
1851                final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1852                if (oldRules == uidRules) return;
1853
1854                mUidRules.put(uid, uidRules);
1855            }
1856
1857            // TODO: notify UID when it has requested targeted updates
1858        }
1859
1860        @Override
1861        public void onMeteredIfacesChanged(String[] meteredIfaces) {
1862            // caller is NPMS, since we only register with them
1863            if (LOGD_RULES) {
1864                log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1865            }
1866
1867            synchronized (mRulesLock) {
1868                mMeteredIfaces.clear();
1869                for (String iface : meteredIfaces) {
1870                    mMeteredIfaces.add(iface);
1871                }
1872            }
1873        }
1874
1875        @Override
1876        public void onRestrictBackgroundChanged(boolean restrictBackground) {
1877            // caller is NPMS, since we only register with them
1878            if (LOGD_RULES) {
1879                log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1880            }
1881
1882            // kick off connectivity change broadcast for active network, since
1883            // global background policy change is radical.
1884            final int networkType = mActiveDefaultNetwork;
1885            if (isNetworkTypeValid(networkType)) {
1886                final NetworkStateTracker tracker = mNetTrackers[networkType];
1887                if (tracker != null) {
1888                    final NetworkInfo info = tracker.getNetworkInfo();
1889                    if (info != null && info.isConnected()) {
1890                        sendConnectedBroadcast(info);
1891                    }
1892                }
1893            }
1894        }
1895    };
1896
1897    /**
1898     * @see ConnectivityManager#setMobileDataEnabled(boolean)
1899     */
1900    public void setMobileDataEnabled(boolean enabled) {
1901        enforceChangePermission();
1902        if (DBG) log("setMobileDataEnabled(" + enabled + ")");
1903
1904        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
1905                (enabled ? ENABLED : DISABLED), 0));
1906    }
1907
1908    private void handleSetMobileData(boolean enabled) {
1909    // TODO - handle this - probably generalize passing in a transport type and send to the
1910    // factories?
1911    }
1912
1913    @Override
1914    public void setPolicyDataEnable(int networkType, boolean enabled) {
1915        // only someone like NPMS should only be calling us
1916        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1917
1918        mHandler.sendMessage(mHandler.obtainMessage(
1919                EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1920    }
1921
1922    private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1923   // TODO - handle this passing to factories
1924//        if (isNetworkTypeValid(networkType)) {
1925//            final NetworkStateTracker tracker = mNetTrackers[networkType];
1926//            if (tracker != null) {
1927//                tracker.setPolicyDataEnable(enabled);
1928//            }
1929//        }
1930    }
1931
1932    private void enforceAccessPermission() {
1933        mContext.enforceCallingOrSelfPermission(
1934                android.Manifest.permission.ACCESS_NETWORK_STATE,
1935                "ConnectivityService");
1936    }
1937
1938    private void enforceChangePermission() {
1939        mContext.enforceCallingOrSelfPermission(
1940                android.Manifest.permission.CHANGE_NETWORK_STATE,
1941                "ConnectivityService");
1942    }
1943
1944    // TODO Make this a special check when it goes public
1945    private void enforceTetherChangePermission() {
1946        mContext.enforceCallingOrSelfPermission(
1947                android.Manifest.permission.CHANGE_NETWORK_STATE,
1948                "ConnectivityService");
1949    }
1950
1951    private void enforceTetherAccessPermission() {
1952        mContext.enforceCallingOrSelfPermission(
1953                android.Manifest.permission.ACCESS_NETWORK_STATE,
1954                "ConnectivityService");
1955    }
1956
1957    private void enforceConnectivityInternalPermission() {
1958        mContext.enforceCallingOrSelfPermission(
1959                android.Manifest.permission.CONNECTIVITY_INTERNAL,
1960                "ConnectivityService");
1961    }
1962
1963    private void enforceMarkNetworkSocketPermission() {
1964        //Media server special case
1965        if (Binder.getCallingUid() == Process.MEDIA_UID) {
1966            return;
1967        }
1968        mContext.enforceCallingOrSelfPermission(
1969                android.Manifest.permission.MARK_NETWORK_SOCKET,
1970                "ConnectivityService");
1971    }
1972
1973    /**
1974     * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1975     * network, we ignore it. If it is for the active network, we send out a
1976     * broadcast. But first, we check whether it might be possible to connect
1977     * to a different network.
1978     * @param info the {@code NetworkInfo} for the network
1979     */
1980    private void handleDisconnect(NetworkInfo info) {
1981
1982        int prevNetType = info.getType();
1983
1984        mNetTrackers[prevNetType].setTeardownRequested(false);
1985        int thisNetId = mNetTrackers[prevNetType].getNetwork().netId;
1986
1987        // Remove idletimer previously setup in {@code handleConnect}
1988// Already in place in new function. This is dead code.
1989//        if (mNetConfigs[prevNetType].isDefault()) {
1990//            removeDataActivityTracking(prevNetType);
1991//        }
1992
1993        /*
1994         * If the disconnected network is not the active one, then don't report
1995         * this as a loss of connectivity. What probably happened is that we're
1996         * getting the disconnect for a network that we explicitly disabled
1997         * in accordance with network preference policies.
1998         */
1999        if (!mNetConfigs[prevNetType].isDefault()) {
2000            List<Integer> pids = mNetRequestersPids[prevNetType];
2001            for (Integer pid : pids) {
2002                // will remove them because the net's no longer connected
2003                // need to do this now as only now do we know the pids and
2004                // can properly null things that are no longer referenced.
2005                reassessPidDns(pid.intValue(), false);
2006            }
2007        }
2008
2009        Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
2010        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2011        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2012        if (info.isFailover()) {
2013            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2014            info.setFailover(false);
2015        }
2016        if (info.getReason() != null) {
2017            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2018        }
2019        if (info.getExtraInfo() != null) {
2020            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2021                    info.getExtraInfo());
2022        }
2023
2024        if (mNetConfigs[prevNetType].isDefault()) {
2025            tryFailover(prevNetType);
2026            if (mActiveDefaultNetwork != -1) {
2027                NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2028                intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2029            } else {
2030                mDefaultInetConditionPublished = 0; // we're not connected anymore
2031                intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2032            }
2033        }
2034        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2035
2036        // Reset interface if no other connections are using the same interface
2037        boolean doReset = true;
2038        LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
2039        if (linkProperties != null) {
2040            String oldIface = linkProperties.getInterfaceName();
2041            if (TextUtils.isEmpty(oldIface) == false) {
2042                for (NetworkStateTracker networkStateTracker : mNetTrackers) {
2043                    if (networkStateTracker == null) continue;
2044                    NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
2045                    if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
2046                        LinkProperties l = networkStateTracker.getLinkProperties();
2047                        if (l == null) continue;
2048                        if (oldIface.equals(l.getInterfaceName())) {
2049                            doReset = false;
2050                            break;
2051                        }
2052                    }
2053                }
2054            }
2055        }
2056
2057        // do this before we broadcast the change
2058// Already done in new function. This is dead code.
2059//        handleConnectivityChange(prevNetType, doReset);
2060
2061        final Intent immediateIntent = new Intent(intent);
2062        immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2063        sendStickyBroadcast(immediateIntent);
2064        sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
2065        /*
2066         * If the failover network is already connected, then immediately send
2067         * out a followup broadcast indicating successful failover
2068         */
2069        if (mActiveDefaultNetwork != -1) {
2070            sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
2071                    getConnectivityChangeDelay());
2072        }
2073        try {
2074//            mNetd.removeNetwork(thisNetId);
2075        } catch (Exception e) {
2076            loge("Exception removing network: " + e);
2077        } finally {
2078            mNetTrackers[prevNetType].setNetId(INVALID_NET_ID);
2079        }
2080    }
2081
2082    private void tryFailover(int prevNetType) {
2083        /*
2084         * If this is a default network, check if other defaults are available.
2085         * Try to reconnect on all available and let them hash it out when
2086         * more than one connects.
2087         */
2088        if (mNetConfigs[prevNetType].isDefault()) {
2089            if (mActiveDefaultNetwork == prevNetType) {
2090                if (DBG) {
2091                    log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2092                }
2093                mActiveDefaultNetwork = -1;
2094                try {
2095                    mNetd.clearDefaultNetId();
2096                } catch (Exception e) {
2097                    loge("Exception clearing default network :" + e);
2098                }
2099            }
2100
2101            // don't signal a reconnect for anything lower or equal priority than our
2102            // current connected default
2103            // TODO - don't filter by priority now - nice optimization but risky
2104//            int currentPriority = -1;
2105//            if (mActiveDefaultNetwork != -1) {
2106//                currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
2107//            }
2108
2109            for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
2110                if (checkType == prevNetType) continue;
2111                if (mNetConfigs[checkType] == null) continue;
2112                if (!mNetConfigs[checkType].isDefault()) continue;
2113                if (mNetTrackers[checkType] == null) continue;
2114
2115// Enabling the isAvailable() optimization caused mobile to not get
2116// selected if it was in the middle of error handling. Specifically
2117// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2118// would not be available and we wouldn't get connected to anything.
2119// So removing the isAvailable() optimization below for now. TODO: This
2120// optimization should work and we need to investigate why it doesn't work.
2121// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2122// complete before it is really complete.
2123
2124//                if (!mNetTrackers[checkType].isAvailable()) continue;
2125
2126//                if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
2127
2128                NetworkStateTracker checkTracker = mNetTrackers[checkType];
2129                NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2130                if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2131                    checkInfo.setFailover(true);
2132                    checkTracker.reconnect();
2133                }
2134                if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
2135            }
2136        }
2137    }
2138
2139    public void sendConnectedBroadcast(NetworkInfo info) {
2140        enforceConnectivityInternalPermission();
2141        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2142        sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
2143    }
2144
2145    private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
2146        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2147        sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
2148    }
2149
2150    private void sendInetConditionBroadcast(NetworkInfo info) {
2151        sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2152    }
2153
2154    private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
2155        if (mLockdownTracker != null) {
2156            info = mLockdownTracker.augmentNetworkInfo(info);
2157        }
2158
2159        Intent intent = new Intent(bcastType);
2160        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2161        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2162        if (info.isFailover()) {
2163            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2164            info.setFailover(false);
2165        }
2166        if (info.getReason() != null) {
2167            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2168        }
2169        if (info.getExtraInfo() != null) {
2170            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2171                    info.getExtraInfo());
2172        }
2173        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2174        return intent;
2175    }
2176
2177    private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2178        sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2179    }
2180
2181    private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2182        sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
2183    }
2184
2185    private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
2186        Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2187        intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2188        intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
2189        intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
2190        final long ident = Binder.clearCallingIdentity();
2191        try {
2192            mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2193                    RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2194        } finally {
2195            Binder.restoreCallingIdentity(ident);
2196        }
2197    }
2198
2199    private void sendStickyBroadcast(Intent intent) {
2200        synchronized(this) {
2201            if (!mSystemReady) {
2202                mInitialBroadcast = new Intent(intent);
2203            }
2204            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2205            if (VDBG) {
2206                log("sendStickyBroadcast: action=" + intent.getAction());
2207            }
2208
2209            final long ident = Binder.clearCallingIdentity();
2210            try {
2211                mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2212            } finally {
2213                Binder.restoreCallingIdentity(ident);
2214            }
2215        }
2216    }
2217
2218    private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2219        if (delayMs <= 0) {
2220            sendStickyBroadcast(intent);
2221        } else {
2222            if (VDBG) {
2223                log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2224                        + intent.getAction());
2225            }
2226            mHandler.sendMessageDelayed(mHandler.obtainMessage(
2227                    EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2228        }
2229    }
2230
2231    void systemReady() {
2232        mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2233        loadGlobalProxy();
2234
2235        synchronized(this) {
2236            mSystemReady = true;
2237            if (mInitialBroadcast != null) {
2238                mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
2239                mInitialBroadcast = null;
2240            }
2241        }
2242        // load the global proxy at startup
2243        mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
2244
2245        // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2246        // for user to unlock device.
2247        if (!updateLockdownVpn()) {
2248            final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2249            mContext.registerReceiver(mUserPresentReceiver, filter);
2250        }
2251    }
2252
2253    private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2254        @Override
2255        public void onReceive(Context context, Intent intent) {
2256            // Try creating lockdown tracker, since user present usually means
2257            // unlocked keystore.
2258            if (updateLockdownVpn()) {
2259                mContext.unregisterReceiver(this);
2260            }
2261        }
2262    };
2263
2264    private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2265        if (((type != mNetworkPreference)
2266                      && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2267                   || (mNetworkPreference == mActiveDefaultNetwork)) {
2268            return false;
2269        }
2270        return true;
2271    }
2272
2273    private void handleConnect(NetworkInfo info) {
2274        final int newNetType = info.getType();
2275
2276        // snapshot isFailover, because sendConnectedBroadcast() resets it
2277        boolean isFailover = info.isFailover();
2278        final NetworkStateTracker thisNet = mNetTrackers[newNetType];
2279        final String thisIface = thisNet.getLinkProperties().getInterfaceName();
2280
2281        if (VDBG) {
2282            log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2283                    + " isFailover" + isFailover);
2284        }
2285
2286        // if this is a default net and other default is running
2287        // kill the one not preferred
2288        if (mNetConfigs[newNetType].isDefault()) {
2289            if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2290                if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
2291                   String teardownPolicy = SystemProperties.get("net.teardownPolicy");
2292                   if (TextUtils.equals(teardownPolicy, "keep") == false) {
2293                        // tear down the other
2294                        NetworkStateTracker otherNet =
2295                                mNetTrackers[mActiveDefaultNetwork];
2296                        if (DBG) {
2297                            log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
2298                                " teardown");
2299                        }
2300                        if (!teardown(otherNet)) {
2301                            loge("Network declined teardown request");
2302                            teardown(thisNet);
2303                            return;
2304                        }
2305                    } else {
2306                        //TODO - remove
2307                        loge("network teardown skipped due to net.teardownPolicy setting");
2308                    }
2309                } else {
2310                       // don't accept this one
2311                        if (VDBG) {
2312                            log("Not broadcasting CONNECT_ACTION " +
2313                                "to torn down network " + info.getTypeName());
2314                        }
2315                        teardown(thisNet);
2316                        return;
2317                }
2318            }
2319            int thisNetId = nextNetId();
2320            thisNet.setNetId(thisNetId);
2321            try {
2322//                mNetd.createNetwork(thisNetId, thisIface);
2323            } catch (Exception e) {
2324                loge("Exception creating network :" + e);
2325                teardown(thisNet);
2326                return;
2327            }
2328// Already in place in new function. This is dead code.
2329//            setupDataActivityTracking(newNetType);
2330            synchronized (ConnectivityService.this) {
2331                // have a new default network, release the transition wakelock in a second
2332                // if it's held.  The second pause is to allow apps to reconnect over the
2333                // new network
2334                if (mNetTransitionWakeLock.isHeld()) {
2335                    mHandler.sendMessageDelayed(mHandler.obtainMessage(
2336                            EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2337                            mNetTransitionWakeLockSerialNumber, 0),
2338                            1000);
2339                }
2340            }
2341            mActiveDefaultNetwork = newNetType;
2342            try {
2343                mNetd.setDefaultNetId(thisNetId);
2344            } catch (Exception e) {
2345                loge("Exception setting default network :" + e);
2346            }
2347            // this will cause us to come up initially as unconnected and switching
2348            // to connected after our normal pause unless somebody reports us as reall
2349            // disconnected
2350            mDefaultInetConditionPublished = 0;
2351            mDefaultConnectionSequence++;
2352            mInetConditionChangeInFlight = false;
2353            // Don't do this - if we never sign in stay, grey
2354            //reportNetworkCondition(mActiveDefaultNetwork, 100);
2355            updateNetworkSettings(thisNet);
2356        } else {
2357            int thisNetId = nextNetId();
2358            thisNet.setNetId(thisNetId);
2359            try {
2360//                mNetd.createNetwork(thisNetId, thisIface);
2361            } catch (Exception e) {
2362                loge("Exception creating network :" + e);
2363                teardown(thisNet);
2364                return;
2365            }
2366        }
2367        thisNet.setTeardownRequested(false);
2368// Already in place in new function. This is dead code.
2369//        updateMtuSizeSettings(thisNet);
2370//        handleConnectivityChange(newNetType, false);
2371        sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
2372
2373        // notify battery stats service about this network
2374        if (thisIface != null) {
2375            try {
2376                BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
2377            } catch (RemoteException e) {
2378                // ignored; service lives in system_server
2379            }
2380        }
2381    }
2382
2383    /** @hide */
2384    @Override
2385    public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2386        enforceConnectivityInternalPermission();
2387        if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2388//        mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2389    }
2390
2391    /**
2392     * Setup data activity tracking for the given network.
2393     *
2394     * Every {@code setupDataActivityTracking} should be paired with a
2395     * {@link #removeDataActivityTracking} for cleanup.
2396     */
2397    private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2398        final String iface = networkAgent.linkProperties.getInterfaceName();
2399
2400        final int timeout;
2401        int type = ConnectivityManager.TYPE_NONE;
2402
2403        if (networkAgent.networkCapabilities.hasTransport(
2404                NetworkCapabilities.TRANSPORT_CELLULAR)) {
2405            timeout = Settings.Global.getInt(mContext.getContentResolver(),
2406                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
2407                                             5);
2408            type = ConnectivityManager.TYPE_MOBILE;
2409        } else if (networkAgent.networkCapabilities.hasTransport(
2410                NetworkCapabilities.TRANSPORT_WIFI)) {
2411            timeout = Settings.Global.getInt(mContext.getContentResolver(),
2412                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
2413                                             0);
2414            type = ConnectivityManager.TYPE_WIFI;
2415        } else {
2416            // do not track any other networks
2417            timeout = 0;
2418        }
2419
2420        if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
2421            try {
2422                mNetd.addIdleTimer(iface, timeout, type);
2423            } catch (Exception e) {
2424                // You shall not crash!
2425                loge("Exception in setupDataActivityTracking " + e);
2426            }
2427        }
2428    }
2429
2430    /**
2431     * Remove data activity tracking when network disconnects.
2432     */
2433    private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2434        final String iface = networkAgent.linkProperties.getInterfaceName();
2435        final NetworkCapabilities caps = networkAgent.networkCapabilities;
2436
2437        if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2438                              caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
2439            try {
2440                // the call fails silently if no idletimer setup for this interface
2441                mNetd.removeIdleTimer(iface);
2442            } catch (Exception e) {
2443                loge("Exception in removeDataActivityTracking " + e);
2444            }
2445        }
2446    }
2447
2448    /**
2449     * After a change in the connectivity state of a network. We're mainly
2450     * concerned with making sure that the list of DNS servers is set up
2451     * according to which networks are connected, and ensuring that the
2452     * right routing table entries exist.
2453     *
2454     * TODO - delete when we're sure all this functionallity is captured.
2455     */
2456    private void handleConnectivityChange(int netType, LinkProperties curLp, boolean doReset) {
2457        int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2458        boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
2459        if (VDBG) {
2460            log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2461                    + " resetMask=" + resetMask);
2462        }
2463
2464        /*
2465         * If a non-default network is enabled, add the host routes that
2466         * will allow it's DNS servers to be accessed.
2467         */
2468        handleDnsConfigurationChange(netType);
2469
2470        LinkProperties newLp = null;
2471
2472        if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2473            newLp = mNetTrackers[netType].getLinkProperties();
2474            if (VDBG) {
2475                log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2476                        " doReset=" + doReset + " resetMask=" + resetMask +
2477                        "\n   curLp=" + curLp +
2478                        "\n   newLp=" + newLp);
2479            }
2480
2481            if (curLp != null) {
2482                if (curLp.isIdenticalInterfaceName(newLp)) {
2483                    CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2484                    if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2485                        for (LinkAddress linkAddr : car.removed) {
2486                            if (linkAddr.getAddress() instanceof Inet4Address) {
2487                                resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2488                            }
2489                            if (linkAddr.getAddress() instanceof Inet6Address) {
2490                                resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2491                            }
2492                        }
2493                        if (DBG) {
2494                            log("handleConnectivityChange: addresses changed" +
2495                                    " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2496                                    "\n   car=" + car);
2497                        }
2498                    } else {
2499                        if (VDBG) {
2500                            log("handleConnectivityChange: addresses are the same reset per" +
2501                                   " doReset linkProperty[" + netType + "]:" +
2502                                   " resetMask=" + resetMask);
2503                        }
2504                    }
2505                } else {
2506                    resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
2507                    if (DBG) {
2508                        log("handleConnectivityChange: interface not not equivalent reset both" +
2509                                " linkProperty[" + netType + "]:" +
2510                                " resetMask=" + resetMask);
2511                    }
2512                }
2513            }
2514            if (mNetConfigs[netType].isDefault()) {
2515                handleApplyDefaultProxy(newLp.getHttpProxy());
2516            }
2517        } else {
2518            if (VDBG) {
2519                log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2520                        " doReset=" + doReset + " resetMask=" + resetMask +
2521                        "\n  curLp=" + curLp +
2522                        "\n  newLp= null");
2523            }
2524        }
2525        mCurrentLinkProperties[netType] = newLp;
2526        boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt,
2527                                        mNetTrackers[netType].getNetwork().netId);
2528
2529        if (resetMask != 0 || resetDns) {
2530            if (VDBG) log("handleConnectivityChange: resetting");
2531            if (curLp != null) {
2532                if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
2533                for (String iface : curLp.getAllInterfaceNames()) {
2534                    if (TextUtils.isEmpty(iface) == false) {
2535                        if (resetMask != 0) {
2536                            if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2537                            NetworkUtils.resetConnections(iface, resetMask);
2538
2539                            // Tell VPN the interface is down. It is a temporary
2540                            // but effective fix to make VPN aware of the change.
2541                            if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2542                                synchronized(mVpns) {
2543                                    for (int i = 0; i < mVpns.size(); i++) {
2544                                        mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2545                                    }
2546                                }
2547                            }
2548                        }
2549                    } else {
2550                        loge("Can't reset connection for type "+netType);
2551                    }
2552                }
2553                if (resetDns) {
2554                    flushVmDnsCache();
2555                    if (VDBG) log("resetting DNS cache for type " + netType);
2556                    try {
2557                        mNetd.flushNetworkDnsCache(mNetTrackers[netType].getNetwork().netId);
2558                    } catch (Exception e) {
2559                        // never crash - catch them all
2560                        if (DBG) loge("Exception resetting dns cache: " + e);
2561                    }
2562                }
2563            }
2564        }
2565
2566        // TODO: Temporary notifying upstread change to Tethering.
2567        //       @see bug/4455071
2568        /** Notify TetheringService if interface name has been changed. */
2569        if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
2570                             PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
2571            if (isTetheringSupported()) {
2572                mTethering.handleTetherIfaceChange();
2573            }
2574        }
2575    }
2576
2577    /**
2578     * Add and remove routes using the old properties (null if not previously connected),
2579     * new properties (null if becoming disconnected).  May even be double null, which
2580     * is a noop.
2581     * Uses isLinkDefault to determine if default routes should be set or conversely if
2582     * host routes should be set to the dns servers
2583     * returns a boolean indicating the routes changed
2584     */
2585    private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2586            boolean isLinkDefault, boolean exempt, int netId) {
2587        Collection<RouteInfo> routesToAdd = null;
2588        CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2589        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
2590        if (curLp != null) {
2591            // check for the delta between the current set and the new
2592            routeDiff = curLp.compareAllRoutes(newLp);
2593            dnsDiff = curLp.compareDnses(newLp);
2594        } else if (newLp != null) {
2595            routeDiff.added = newLp.getAllRoutes();
2596            dnsDiff.added = newLp.getDnses();
2597        }
2598
2599        boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2600
2601        for (RouteInfo r : routeDiff.removed) {
2602            if (isLinkDefault || ! r.isDefaultRoute()) {
2603                if (VDBG) log("updateRoutes: default remove route r=" + r);
2604                removeRoute(curLp, r, TO_DEFAULT_TABLE, netId);
2605            }
2606            if (isLinkDefault == false) {
2607                // remove from a secondary route table
2608                removeRoute(curLp, r, TO_SECONDARY_TABLE, netId);
2609            }
2610        }
2611
2612        for (RouteInfo r :  routeDiff.added) {
2613            if (isLinkDefault || ! r.isDefaultRoute()) {
2614                addRoute(newLp, r, TO_DEFAULT_TABLE, exempt, netId);
2615            } else {
2616                // add to a secondary route table
2617                addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT, netId);
2618
2619                // many radios add a default route even when we don't want one.
2620                // remove the default route unless somebody else has asked for it
2621                String ifaceName = newLp.getInterfaceName();
2622                synchronized (mRoutesLock) {
2623                    if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2624                        if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2625                        try {
2626                            mNetd.removeRoute(netId, r);
2627                        } catch (Exception e) {
2628                            // never crash - catch them all
2629                            if (DBG) loge("Exception trying to remove a route: " + e);
2630                        }
2631                    }
2632                }
2633            }
2634        }
2635
2636        return routesChanged;
2637    }
2638
2639    /**
2640     * Reads the network specific MTU size from reources.
2641     * and set it on it's iface.
2642     */
2643    private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2644        final String iface = newLp.getInterfaceName();
2645        final int mtu = newLp.getMtu();
2646        if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2647            if (VDBG) log("identical MTU - not setting");
2648            return;
2649        }
2650
2651        if (mtu < 68 || mtu > 10000) {
2652            loge("Unexpected mtu value: " + mtu + ", " + iface);
2653            return;
2654        }
2655
2656        try {
2657            if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2658            mNetd.setMtu(iface, mtu);
2659        } catch (Exception e) {
2660            Slog.e(TAG, "exception in setMtu()" + e);
2661        }
2662    }
2663
2664    /**
2665     * Reads the network specific TCP buffer sizes from SystemProperties
2666     * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2667     * wide use
2668     */
2669    private void updateNetworkSettings(NetworkStateTracker nt) {
2670        String key = nt.getTcpBufferSizesPropName();
2671        String bufferSizes = key == null ? null : SystemProperties.get(key);
2672
2673        if (TextUtils.isEmpty(bufferSizes)) {
2674            if (VDBG) log(key + " not found in system properties. Using defaults");
2675
2676            // Setting to default values so we won't be stuck to previous values
2677            key = "net.tcp.buffersize.default";
2678            bufferSizes = SystemProperties.get(key);
2679        }
2680
2681        // Set values in kernel
2682        if (bufferSizes.length() != 0) {
2683            if (VDBG) {
2684                log("Setting TCP values: [" + bufferSizes
2685                        + "] which comes from [" + key + "]");
2686            }
2687            setBufferSize(bufferSizes);
2688        }
2689
2690        final String defaultRwndKey = "net.tcp.default_init_rwnd";
2691        int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
2692        Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
2693            Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
2694        final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2695        if (rwndValue != 0) {
2696            SystemProperties.set(sysctlKey, rwndValue.toString());
2697        }
2698    }
2699
2700    /**
2701     * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2702     * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2703     *
2704     * @param bufferSizes in the format of "readMin, readInitial, readMax,
2705     *        writeMin, writeInitial, writeMax"
2706     */
2707    private void setBufferSize(String bufferSizes) {
2708        try {
2709            String[] values = bufferSizes.split(",");
2710
2711            if (values.length == 6) {
2712              final String prefix = "/sys/kernel/ipv4/tcp_";
2713                FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2714                FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2715                FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2716                FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2717                FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2718                FileUtils.stringToFile(prefix + "wmem_max", values[5]);
2719            } else {
2720                loge("Invalid buffersize string: " + bufferSizes);
2721            }
2722        } catch (IOException e) {
2723            loge("Can't set tcp buffer sizes:" + e);
2724        }
2725    }
2726
2727    /**
2728     * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2729     * on the highest priority active net which this process requested.
2730     * If there aren't any, clear it out
2731     */
2732    private void reassessPidDns(int pid, boolean doBump)
2733    {
2734        if (VDBG) log("reassessPidDns for pid " + pid);
2735        Integer myPid = new Integer(pid);
2736        for(int i : mPriorityList) {
2737            if (mNetConfigs[i].isDefault()) {
2738                continue;
2739            }
2740            NetworkStateTracker nt = mNetTrackers[i];
2741            if (nt.getNetworkInfo().isConnected() &&
2742                    !nt.isTeardownRequested()) {
2743                LinkProperties p = nt.getLinkProperties();
2744                if (p == null) continue;
2745                if (mNetRequestersPids[i].contains(myPid)) {
2746                    try {
2747                        // TODO: Reimplement this via local variable in bionic.
2748                        // mNetd.setDnsNetworkForPid(nt.getNetwork().netId, pid);
2749                    } catch (Exception e) {
2750                        Slog.e(TAG, "exception reasseses pid dns: " + e);
2751                    }
2752                    return;
2753                }
2754           }
2755        }
2756        // nothing found - delete
2757        try {
2758            // TODO: Reimplement this via local variable in bionic.
2759            // mNetd.clearDnsNetworkForPid(pid);
2760        } catch (Exception e) {
2761            Slog.e(TAG, "exception clear interface from pid: " + e);
2762        }
2763    }
2764
2765    private void flushVmDnsCache() {
2766        /*
2767         * Tell the VMs to toss their DNS caches
2768         */
2769        Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2770        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
2771        /*
2772         * Connectivity events can happen before boot has completed ...
2773         */
2774        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2775        final long ident = Binder.clearCallingIdentity();
2776        try {
2777            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2778        } finally {
2779            Binder.restoreCallingIdentity(ident);
2780        }
2781    }
2782
2783    // Caller must grab mDnsLock.
2784    private void updateDnsLocked(String network, int netId,
2785            Collection<InetAddress> dnses, String domains) {
2786        int last = 0;
2787        if (dnses.size() == 0 && mDefaultDns != null) {
2788            dnses = new ArrayList();
2789            dnses.add(mDefaultDns);
2790            if (DBG) {
2791                loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
2792            }
2793        }
2794
2795        try {
2796            mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), domains);
2797
2798            for (InetAddress dns : dnses) {
2799                ++last;
2800                String key = "net.dns" + last;
2801                String value = dns.getHostAddress();
2802                SystemProperties.set(key, value);
2803            }
2804            for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2805                String key = "net.dns" + i;
2806                SystemProperties.set(key, "");
2807            }
2808            mNumDnsEntries = last;
2809        } catch (Exception e) {
2810            loge("exception setting default dns interface: " + e);
2811        }
2812    }
2813
2814    private void handleDnsConfigurationChange(int netType) {
2815        // add default net's dns entries
2816        NetworkStateTracker nt = mNetTrackers[netType];
2817        if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
2818            LinkProperties p = nt.getLinkProperties();
2819            if (p == null) return;
2820            Collection<InetAddress> dnses = p.getDnses();
2821            int netId = nt.getNetwork().netId;
2822            if (mNetConfigs[netType].isDefault()) {
2823                String network = nt.getNetworkInfo().getTypeName();
2824                synchronized (mDnsLock) {
2825                    updateDnsLocked(network, netId, dnses, p.getDomains());
2826                }
2827            } else {
2828                try {
2829                    mNetd.setDnsServersForNetwork(netId,
2830                            NetworkUtils.makeStrings(dnses), p.getDomains());
2831                } catch (Exception e) {
2832                    if (DBG) loge("exception setting dns servers: " + e);
2833                }
2834                // set per-pid dns for attached secondary nets
2835                List<Integer> pids = mNetRequestersPids[netType];
2836                for (Integer pid : pids) {
2837                    try {
2838                        // TODO: Reimplement this via local variable in bionic.
2839                        // mNetd.setDnsNetworkForPid(netId, pid);
2840                    } catch (Exception e) {
2841                        Slog.e(TAG, "exception setting interface for pid: " + e);
2842                    }
2843                }
2844            }
2845            flushVmDnsCache();
2846        }
2847    }
2848
2849    private int getRestoreDefaultNetworkDelay(int networkType) {
2850        String restoreDefaultNetworkDelayStr = SystemProperties.get(
2851                NETWORK_RESTORE_DELAY_PROP_NAME);
2852        if(restoreDefaultNetworkDelayStr != null &&
2853                restoreDefaultNetworkDelayStr.length() != 0) {
2854            try {
2855                return Integer.valueOf(restoreDefaultNetworkDelayStr);
2856            } catch (NumberFormatException e) {
2857            }
2858        }
2859        // if the system property isn't set, use the value for the apn type
2860        int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2861
2862        if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2863                (mNetConfigs[networkType] != null)) {
2864            ret = mNetConfigs[networkType].restoreTime;
2865        }
2866        return ret;
2867    }
2868
2869    @Override
2870    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2871        final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
2872        if (mContext.checkCallingOrSelfPermission(
2873                android.Manifest.permission.DUMP)
2874                != PackageManager.PERMISSION_GRANTED) {
2875            pw.println("Permission Denial: can't dump ConnectivityService " +
2876                    "from from pid=" + Binder.getCallingPid() + ", uid=" +
2877                    Binder.getCallingUid());
2878            return;
2879        }
2880
2881        NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
2882        pw.print("Active default network: ");
2883        if (defaultNai == null) {
2884            pw.println("none");
2885        } else {
2886            pw.println(defaultNai.network.netId);
2887        }
2888        pw.println();
2889
2890        pw.println("Current Networks:");
2891        pw.increaseIndent();
2892        for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2893            pw.println(nai.toString());
2894            pw.increaseIndent();
2895            pw.println("Requests:");
2896            pw.increaseIndent();
2897            for (int i = 0; i < nai.networkRequests.size(); i++) {
2898                pw.println(nai.networkRequests.valueAt(i).toString());
2899            }
2900            pw.decreaseIndent();
2901            pw.println("Lingered:");
2902            pw.increaseIndent();
2903            for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
2904            pw.decreaseIndent();
2905            pw.decreaseIndent();
2906        }
2907        pw.decreaseIndent();
2908        pw.println();
2909
2910        pw.println("Network Requests:");
2911        pw.increaseIndent();
2912        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2913            pw.println(nri.toString());
2914        }
2915        pw.println();
2916        pw.decreaseIndent();
2917
2918        synchronized (this) {
2919            pw.println("NetworkTranstionWakeLock is currently " +
2920                    (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2921            pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2922        }
2923        pw.println();
2924
2925        mTethering.dump(fd, pw, args);
2926
2927        if (mInetLog != null) {
2928            pw.println();
2929            pw.println("Inet condition reports:");
2930            pw.increaseIndent();
2931            for(int i = 0; i < mInetLog.size(); i++) {
2932                pw.println(mInetLog.get(i));
2933            }
2934            pw.decreaseIndent();
2935        }
2936    }
2937
2938    // must be stateless - things change under us.
2939    private class NetworkStateTrackerHandler extends Handler {
2940        public NetworkStateTrackerHandler(Looper looper) {
2941            super(looper);
2942        }
2943
2944        @Override
2945        public void handleMessage(Message msg) {
2946            NetworkInfo info;
2947            switch (msg.what) {
2948                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
2949                    handleAsyncChannelHalfConnect(msg);
2950                    break;
2951                }
2952                case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2953                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2954                    if (nai != null) nai.asyncChannel.disconnect();
2955                    break;
2956                }
2957                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2958                    handleAsyncChannelDisconnected(msg);
2959                    break;
2960                }
2961                case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
2962                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2963                    if (nai == null) {
2964                        loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
2965                    } else {
2966                        updateCapabilities(nai, (NetworkCapabilities)msg.obj);
2967                    }
2968                    break;
2969                }
2970                case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
2971                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2972                    if (nai == null) {
2973                        loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
2974                    } else {
2975                        LinkProperties oldLp = nai.linkProperties;
2976                        nai.linkProperties = (LinkProperties)msg.obj;
2977                        updateLinkProperties(nai, oldLp);
2978                    }
2979                    break;
2980                }
2981                case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
2982                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2983                    if (nai == null) {
2984                        loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
2985                        break;
2986                    }
2987                    info = (NetworkInfo) msg.obj;
2988                    updateNetworkInfo(nai, info);
2989                    break;
2990                }
2991                case NetworkMonitor.EVENT_NETWORK_VALIDATED: {
2992                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
2993                    handleConnectionValidated(nai);
2994                    break;
2995                }
2996                case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
2997                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
2998                    handleLingerComplete(nai);
2999                    break;
3000                }
3001                case NetworkStateTracker.EVENT_STATE_CHANGED: {
3002                    info = (NetworkInfo) msg.obj;
3003                    NetworkInfo.State state = info.getState();
3004
3005                    if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
3006                            (state == NetworkInfo.State.DISCONNECTED) ||
3007                            (state == NetworkInfo.State.SUSPENDED)) {
3008                        log("ConnectivityChange for " +
3009                            info.getTypeName() + ": " +
3010                            state + "/" + info.getDetailedState());
3011                    }
3012
3013                    // Since mobile has the notion of a network/apn that can be used for
3014                    // provisioning we need to check every time we're connected as
3015                    // CaptiveProtalTracker won't detected it because DCT doesn't report it
3016                    // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
3017                    // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
3018                    // is received by MDST and sent here as EVENT_STATE_CHANGED.
3019                    if (ConnectivityManager.isNetworkTypeMobile(info.getType())
3020                            && (0 != Settings.Global.getInt(mContext.getContentResolver(),
3021                                        Settings.Global.DEVICE_PROVISIONED, 0))
3022                            && (((state == NetworkInfo.State.CONNECTED)
3023                                    && (info.getType() == ConnectivityManager.TYPE_MOBILE))
3024                                || info.isConnectedToProvisioningNetwork())) {
3025                        log("ConnectivityChange checkMobileProvisioning for"
3026                                + " TYPE_MOBILE or ProvisioningNetwork");
3027                        checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
3028                    }
3029
3030                    EventLogTags.writeConnectivityStateChanged(
3031                            info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
3032
3033                    if (info.isConnectedToProvisioningNetwork()) {
3034                        /**
3035                         * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
3036                         * for now its an in between network, its a network that
3037                         * is actually a default network but we don't want it to be
3038                         * announced as such to keep background applications from
3039                         * trying to use it. It turns out that some still try so we
3040                         * take the additional step of clearing any default routes
3041                         * to the link that may have incorrectly setup by the lower
3042                         * levels.
3043                         */
3044                        LinkProperties lp = getLinkPropertiesForTypeInternal(info.getType());
3045                        if (DBG) {
3046                            log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
3047                        }
3048
3049                        // Clear any default routes setup by the radio so
3050                        // any activity by applications trying to use this
3051                        // connection will fail until the provisioning network
3052                        // is enabled.
3053                        for (RouteInfo r : lp.getRoutes()) {
3054                            removeRoute(lp, r, TO_DEFAULT_TABLE,
3055                                        mNetTrackers[info.getType()].getNetwork().netId);
3056                        }
3057                    } else if (state == NetworkInfo.State.DISCONNECTED) {
3058                    } else if (state == NetworkInfo.State.SUSPENDED) {
3059                    } else if (state == NetworkInfo.State.CONNECTED) {
3060                    //    handleConnect(info);
3061                    }
3062                    if (mLockdownTracker != null) {
3063                        mLockdownTracker.onNetworkInfoChanged(info);
3064                    }
3065                    break;
3066                }
3067                case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
3068                    info = (NetworkInfo) msg.obj;
3069                    // TODO: Temporary allowing network configuration
3070                    //       change not resetting sockets.
3071                    //       @see bug/4455071
3072                    handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()],
3073                            false);
3074                    break;
3075                }
3076                case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
3077                    info = (NetworkInfo) msg.obj;
3078                    int type = info.getType();
3079                    if (mNetConfigs[type].isDefault()) updateNetworkSettings(mNetTrackers[type]);
3080                    break;
3081                }
3082            }
3083        }
3084    }
3085
3086    private void handleAsyncChannelHalfConnect(Message msg) {
3087        AsyncChannel ac = (AsyncChannel) msg.obj;
3088        if (mNetworkFactories.contains(ac)) {
3089            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
3090                if (VDBG) log("NetworkFactory connected");
3091                // A network factory has connected.  Send it all current NetworkRequests.
3092                for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3093                    NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
3094                    ac.sendMessage(NetworkFactoryProtocol.CMD_REQUEST_NETWORK,
3095                            (nai != null ? nai.currentScore : 0), 0, nri.request);
3096                }
3097            } else {
3098                loge("Error connecting NetworkFactory");
3099                mNetworkFactories.remove(ac);
3100            }
3101        } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
3102            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
3103                if (VDBG) log("NetworkAgent connected");
3104                // A network agent has requested a connection.  Establish the connection.
3105                mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
3106                        sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
3107            } else {
3108                loge("Error connecting NetworkAgent");
3109                NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
3110                try {
3111                    mNetworkAgentInfoForType[nai.networkInfo.getType()].remove(nai);
3112                } catch (NullPointerException e) {}
3113                if (nai != null) {
3114                    mNetworkForNetId.remove(nai.network.netId);
3115                }
3116            }
3117        }
3118    }
3119    private void handleAsyncChannelDisconnected(Message msg) {
3120        NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3121        if (nai != null) {
3122            if (DBG) {
3123                log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
3124            }
3125            // A network agent has disconnected.
3126            // Tell netd to clean up the configuration for this network
3127            // (routing rules, DNS, etc).
3128            try {
3129                mNetd.removeNetwork(nai.network.netId);
3130            } catch (Exception e) {
3131                loge("Exception removing network: " + e);
3132            }
3133            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
3134            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
3135            mNetworkAgentInfos.remove(msg.replyTo);
3136            updateClat(null, nai.linkProperties, nai);
3137            try {
3138                mNetworkAgentInfoForType[nai.networkInfo.getType()].remove(nai);
3139            } catch (NullPointerException e) {}
3140
3141            mNetworkForNetId.remove(nai.network.netId);
3142            // Since we've lost the network, go through all the requests that
3143            // it was satisfying and see if any other factory can satisfy them.
3144            final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
3145            for (int i = 0; i < nai.networkRequests.size(); i++) {
3146                NetworkRequest request = nai.networkRequests.valueAt(i);
3147                NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
3148                if (VDBG) {
3149                    log(" checking request " + request + ", currentNetwork = " +
3150                            currentNetwork != null ? currentNetwork.name() : "null");
3151                }
3152                if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
3153                    mNetworkForRequestId.remove(request.requestId);
3154                    sendUpdatedScoreToFactories(request, 0);
3155                    NetworkAgentInfo alternative = null;
3156                    for (Map.Entry entry : mNetworkAgentInfos.entrySet()) {
3157                        NetworkAgentInfo existing = (NetworkAgentInfo)entry.getValue();
3158                        if (existing.networkInfo.isConnected() &&
3159                                request.networkCapabilities.satisfiedByNetworkCapabilities(
3160                                existing.networkCapabilities) &&
3161                                (alternative == null ||
3162                                 alternative.currentScore < existing.currentScore)) {
3163                            alternative = existing;
3164                        }
3165                    }
3166                    if (alternative != null && !toActivate.contains(alternative)) {
3167                        toActivate.add(alternative);
3168                    }
3169                }
3170            }
3171            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
3172                removeDataActivityTracking(nai);
3173                mActiveDefaultNetwork = ConnectivityManager.TYPE_NONE;
3174            }
3175            for (NetworkAgentInfo networkToActivate : toActivate) {
3176                networkToActivate.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
3177            }
3178        }
3179    }
3180
3181    private void handleRegisterNetworkRequest(Message msg) {
3182        final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3183        final NetworkCapabilities newCap = nri.request.networkCapabilities;
3184        int score = 0;
3185
3186        // Check for the best currently alive network that satisfies this request
3187        NetworkAgentInfo bestNetwork = null;
3188        for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
3189            if (VDBG) log("handleRegisterNetworkRequest checking " + network.name());
3190            if (newCap.satisfiedByNetworkCapabilities(network.networkCapabilities)) {
3191                if (VDBG) log("apparently satisfied.  currentScore=" + network.currentScore);
3192                if ((bestNetwork == null) || bestNetwork.currentScore < network.currentScore) {
3193                    bestNetwork = network;
3194                }
3195            }
3196        }
3197        if (bestNetwork != null) {
3198            if (VDBG) log("using " + bestNetwork.name());
3199            bestNetwork.networkRequests.put(nri.request.requestId, nri.request);
3200            notifyNetworkCallback(bestNetwork, nri);
3201            score = bestNetwork.currentScore;
3202        }
3203        mNetworkRequests.put(nri.request, nri);
3204        if (msg.what == EVENT_REGISTER_NETWORK_REQUEST) {
3205            if (DBG) log("sending new NetworkRequest to factories");
3206            for (AsyncChannel ac : mNetworkFactories) {
3207                ac.sendMessage(NetworkFactoryProtocol.CMD_REQUEST_NETWORK, score, 0, nri.request);
3208            }
3209        }
3210    }
3211
3212    private void handleReleaseNetworkRequest(NetworkRequest request) {
3213        if (DBG) log("releasing NetworkRequest " + request);
3214        NetworkRequestInfo nri = mNetworkRequests.remove(request);
3215        if (nri != null) {
3216            // tell the network currently servicing this that it's no longer interested
3217            NetworkAgentInfo affectedNetwork = mNetworkForRequestId.get(nri.request.requestId);
3218            if (affectedNetwork != null) {
3219                affectedNetwork.networkRequests.remove(nri.request.requestId);
3220                if (VDBG) {
3221                    log(" Removing from current network " + affectedNetwork.name() + ", leaving " +
3222                            affectedNetwork.networkRequests.size() + " requests.");
3223                }
3224            }
3225
3226            if (nri.isRequest) {
3227                for (AsyncChannel factory : mNetworkFactories) {
3228                    factory.sendMessage(NetworkFactoryProtocol.CMD_CANCEL_REQUEST, nri.request);
3229                }
3230
3231                if (affectedNetwork != null) {
3232                    // check if this network still has live requests - otherwise, tear down
3233                    // TODO - probably push this to the NF/NA
3234                    boolean keep = false;
3235                    for (int i = 0; i < affectedNetwork.networkRequests.size(); i++) {
3236                        NetworkRequest r = affectedNetwork.networkRequests.valueAt(i);
3237                        if (mNetworkRequests.get(r).isRequest) {
3238                            keep = true;
3239                            break;
3240                        }
3241                    }
3242                    if (keep == false) {
3243                        if (DBG) log("no live requests for " + affectedNetwork.name() +
3244                                "; disconnecting");
3245                        affectedNetwork.asyncChannel.disconnect();
3246                    }
3247                }
3248            }
3249            callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
3250        }
3251    }
3252
3253    private class InternalHandler extends Handler {
3254        public InternalHandler(Looper looper) {
3255            super(looper);
3256        }
3257
3258        @Override
3259        public void handleMessage(Message msg) {
3260            NetworkInfo info;
3261            switch (msg.what) {
3262                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
3263                    String causedBy = null;
3264                    synchronized (ConnectivityService.this) {
3265                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3266                                mNetTransitionWakeLock.isHeld()) {
3267                            mNetTransitionWakeLock.release();
3268                            causedBy = mNetTransitionWakeLockCausedBy;
3269                        }
3270                    }
3271                    if (causedBy != null) {
3272                        log("NetTransition Wakelock for " + causedBy + " released by timeout");
3273                    }
3274                    break;
3275                }
3276                case EVENT_RESTORE_DEFAULT_NETWORK: {
3277                    FeatureUser u = (FeatureUser)msg.obj;
3278                    u.expire();
3279                    break;
3280                }
3281                case EVENT_INET_CONDITION_CHANGE: {
3282                    int netType = msg.arg1;
3283                    int condition = msg.arg2;
3284                    handleInetConditionChange(netType, condition);
3285                    break;
3286                }
3287                case EVENT_INET_CONDITION_HOLD_END: {
3288                    int netType = msg.arg1;
3289                    int sequence = msg.arg2;
3290                    handleInetConditionHoldEnd(netType, sequence);
3291                    break;
3292                }
3293                case EVENT_SET_MOBILE_DATA: {
3294                    boolean enabled = (msg.arg1 == ENABLED);
3295                    handleSetMobileData(enabled);
3296                    break;
3297                }
3298                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
3299                    handleDeprecatedGlobalHttpProxy();
3300                    break;
3301                }
3302                case EVENT_SET_DEPENDENCY_MET: {
3303                    boolean met = (msg.arg1 == ENABLED);
3304                    handleSetDependencyMet(msg.arg2, met);
3305                    break;
3306                }
3307                case EVENT_SEND_STICKY_BROADCAST_INTENT: {
3308                    Intent intent = (Intent)msg.obj;
3309                    sendStickyBroadcast(intent);
3310                    break;
3311                }
3312                case EVENT_SET_POLICY_DATA_ENABLE: {
3313                    final int networkType = msg.arg1;
3314                    final boolean enabled = msg.arg2 == ENABLED;
3315                    handleSetPolicyDataEnable(networkType, enabled);
3316                    break;
3317                }
3318                case EVENT_VPN_STATE_CHANGED: {
3319                    if (mLockdownTracker != null) {
3320                        mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3321                    }
3322                    break;
3323                }
3324                case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3325                    int tag = mEnableFailFastMobileDataTag.get();
3326                    if (msg.arg1 == tag) {
3327                        MobileDataStateTracker mobileDst =
3328                            (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3329                        if (mobileDst != null) {
3330                            mobileDst.setEnableFailFastMobileData(msg.arg2);
3331                        }
3332                    } else {
3333                        log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3334                                + " != tag:" + tag);
3335                    }
3336                    break;
3337                }
3338                case EVENT_SAMPLE_INTERVAL_ELAPSED: {
3339                    handleNetworkSamplingTimeout();
3340                    break;
3341                }
3342                case EVENT_PROXY_HAS_CHANGED: {
3343                    handleApplyDefaultProxy((ProxyInfo)msg.obj);
3344                    break;
3345                }
3346                case EVENT_REGISTER_NETWORK_FACTORY: {
3347                    handleRegisterNetworkFactory((Messenger)msg.obj);
3348                    break;
3349                }
3350                case EVENT_REGISTER_NETWORK_AGENT: {
3351                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
3352                    break;
3353                }
3354                case EVENT_REGISTER_NETWORK_REQUEST:
3355                case EVENT_REGISTER_NETWORK_LISTENER: {
3356                    handleRegisterNetworkRequest(msg);
3357                    break;
3358                }
3359                case EVENT_RELEASE_NETWORK_REQUEST: {
3360                    handleReleaseNetworkRequest((NetworkRequest) msg.obj);
3361                    break;
3362                }
3363            }
3364        }
3365    }
3366
3367    // javadoc from interface
3368    public int tether(String iface) {
3369        enforceTetherChangePermission();
3370
3371        if (isTetheringSupported()) {
3372            return mTethering.tether(iface);
3373        } else {
3374            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3375        }
3376    }
3377
3378    // javadoc from interface
3379    public int untether(String iface) {
3380        enforceTetherChangePermission();
3381
3382        if (isTetheringSupported()) {
3383            return mTethering.untether(iface);
3384        } else {
3385            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3386        }
3387    }
3388
3389    // javadoc from interface
3390    public int getLastTetherError(String iface) {
3391        enforceTetherAccessPermission();
3392
3393        if (isTetheringSupported()) {
3394            return mTethering.getLastTetherError(iface);
3395        } else {
3396            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3397        }
3398    }
3399
3400    // TODO - proper iface API for selection by property, inspection, etc
3401    public String[] getTetherableUsbRegexs() {
3402        enforceTetherAccessPermission();
3403        if (isTetheringSupported()) {
3404            return mTethering.getTetherableUsbRegexs();
3405        } else {
3406            return new String[0];
3407        }
3408    }
3409
3410    public String[] getTetherableWifiRegexs() {
3411        enforceTetherAccessPermission();
3412        if (isTetheringSupported()) {
3413            return mTethering.getTetherableWifiRegexs();
3414        } else {
3415            return new String[0];
3416        }
3417    }
3418
3419    public String[] getTetherableBluetoothRegexs() {
3420        enforceTetherAccessPermission();
3421        if (isTetheringSupported()) {
3422            return mTethering.getTetherableBluetoothRegexs();
3423        } else {
3424            return new String[0];
3425        }
3426    }
3427
3428    public int setUsbTethering(boolean enable) {
3429        enforceTetherChangePermission();
3430        if (isTetheringSupported()) {
3431            return mTethering.setUsbTethering(enable);
3432        } else {
3433            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3434        }
3435    }
3436
3437    // TODO - move iface listing, queries, etc to new module
3438    // javadoc from interface
3439    public String[] getTetherableIfaces() {
3440        enforceTetherAccessPermission();
3441        return mTethering.getTetherableIfaces();
3442    }
3443
3444    public String[] getTetheredIfaces() {
3445        enforceTetherAccessPermission();
3446        return mTethering.getTetheredIfaces();
3447    }
3448
3449    public String[] getTetheringErroredIfaces() {
3450        enforceTetherAccessPermission();
3451        return mTethering.getErroredIfaces();
3452    }
3453
3454    // if ro.tether.denied = true we default to no tethering
3455    // gservices could set the secure setting to 1 though to enable it on a build where it
3456    // had previously been turned off.
3457    public boolean isTetheringSupported() {
3458        enforceTetherAccessPermission();
3459        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
3460        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3461                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
3462        return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3463                mTethering.getTetherableWifiRegexs().length != 0 ||
3464                mTethering.getTetherableBluetoothRegexs().length != 0) &&
3465                mTethering.getUpstreamIfaceTypes().length != 0);
3466    }
3467
3468    // An API NetworkStateTrackers can call when they lose their network.
3469    // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3470    // whichever happens first.  The timer is started by the first caller and not
3471    // restarted by subsequent callers.
3472    public void requestNetworkTransitionWakelock(String forWhom) {
3473        enforceConnectivityInternalPermission();
3474        synchronized (this) {
3475            if (mNetTransitionWakeLock.isHeld()) return;
3476            mNetTransitionWakeLockSerialNumber++;
3477            mNetTransitionWakeLock.acquire();
3478            mNetTransitionWakeLockCausedBy = forWhom;
3479        }
3480        mHandler.sendMessageDelayed(mHandler.obtainMessage(
3481                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
3482                mNetTransitionWakeLockSerialNumber, 0),
3483                mNetTransitionWakeLockTimeout);
3484        return;
3485    }
3486
3487    // 100 percent is full good, 0 is full bad.
3488    public void reportInetCondition(int networkType, int percentage) {
3489        if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
3490        mContext.enforceCallingOrSelfPermission(
3491                android.Manifest.permission.STATUS_BAR,
3492                "ConnectivityService");
3493
3494        if (DBG) {
3495            int pid = getCallingPid();
3496            int uid = getCallingUid();
3497            String s = pid + "(" + uid + ") reports inet is " +
3498                (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3499                "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3500            mInetLog.add(s);
3501            while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3502                mInetLog.remove(0);
3503            }
3504        }
3505        mHandler.sendMessage(mHandler.obtainMessage(
3506            EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3507    }
3508
3509    public void reportBadNetwork(Network network) {
3510        //TODO
3511    }
3512
3513    private void handleInetConditionChange(int netType, int condition) {
3514        if (mActiveDefaultNetwork == -1) {
3515            if (DBG) log("handleInetConditionChange: no active default network - ignore");
3516            return;
3517        }
3518        if (mActiveDefaultNetwork != netType) {
3519            if (DBG) log("handleInetConditionChange: net=" + netType +
3520                            " != default=" + mActiveDefaultNetwork + " - ignore");
3521            return;
3522        }
3523        if (VDBG) {
3524            log("handleInetConditionChange: net=" +
3525                    netType + ", condition=" + condition +
3526                    ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
3527        }
3528        mDefaultInetCondition = condition;
3529        int delay;
3530        if (mInetConditionChangeInFlight == false) {
3531            if (VDBG) log("handleInetConditionChange: starting a change hold");
3532            // setup a new hold to debounce this
3533            if (mDefaultInetCondition > 50) {
3534                delay = Settings.Global.getInt(mContext.getContentResolver(),
3535                        Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
3536            } else {
3537                delay = Settings.Global.getInt(mContext.getContentResolver(),
3538                        Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
3539            }
3540            mInetConditionChangeInFlight = true;
3541            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
3542                    mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
3543        } else {
3544            // we've set the new condition, when this hold ends that will get picked up
3545            if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
3546        }
3547    }
3548
3549    private void handleInetConditionHoldEnd(int netType, int sequence) {
3550        if (DBG) {
3551            log("handleInetConditionHoldEnd: net=" + netType +
3552                    ", condition=" + mDefaultInetCondition +
3553                    ", published condition=" + mDefaultInetConditionPublished);
3554        }
3555        mInetConditionChangeInFlight = false;
3556
3557        if (mActiveDefaultNetwork == -1) {
3558            if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
3559            return;
3560        }
3561        if (mDefaultConnectionSequence != sequence) {
3562            if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
3563            return;
3564        }
3565        // TODO: Figure out why this optimization sometimes causes a
3566        //       change in mDefaultInetCondition to be missed and the
3567        //       UI to not be updated.
3568        //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3569        //    if (DBG) log("no change in condition - aborting");
3570        //    return;
3571        //}
3572        NetworkInfo networkInfo = getNetworkInfoForType(mActiveDefaultNetwork);
3573        if (networkInfo.isConnected() == false) {
3574            if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
3575            return;
3576        }
3577        mDefaultInetConditionPublished = mDefaultInetCondition;
3578        sendInetConditionBroadcast(networkInfo);
3579        return;
3580    }
3581
3582    public ProxyInfo getProxy() {
3583        // this information is already available as a world read/writable jvm property
3584        // so this API change wouldn't have a benifit.  It also breaks the passing
3585        // of proxy info to all the JVMs.
3586        // enforceAccessPermission();
3587        synchronized (mProxyLock) {
3588            ProxyInfo ret = mGlobalProxy;
3589            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3590            return ret;
3591        }
3592    }
3593
3594    public void setGlobalProxy(ProxyInfo proxyProperties) {
3595        enforceConnectivityInternalPermission();
3596
3597        synchronized (mProxyLock) {
3598            if (proxyProperties == mGlobalProxy) return;
3599            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3600            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3601
3602            String host = "";
3603            int port = 0;
3604            String exclList = "";
3605            String pacFileUrl = "";
3606            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3607                    (proxyProperties.getPacFileUrl() != null))) {
3608                if (!proxyProperties.isValid()) {
3609                    if (DBG)
3610                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3611                    return;
3612                }
3613                mGlobalProxy = new ProxyInfo(proxyProperties);
3614                host = mGlobalProxy.getHost();
3615                port = mGlobalProxy.getPort();
3616                exclList = mGlobalProxy.getExclusionListAsString();
3617                if (proxyProperties.getPacFileUrl() != null) {
3618                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
3619                }
3620            } else {
3621                mGlobalProxy = null;
3622            }
3623            ContentResolver res = mContext.getContentResolver();
3624            final long token = Binder.clearCallingIdentity();
3625            try {
3626                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3627                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3628                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3629                        exclList);
3630                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
3631            } finally {
3632                Binder.restoreCallingIdentity(token);
3633            }
3634        }
3635
3636        if (mGlobalProxy == null) {
3637            proxyProperties = mDefaultProxy;
3638        }
3639        sendProxyBroadcast(proxyProperties);
3640    }
3641
3642    private void loadGlobalProxy() {
3643        ContentResolver res = mContext.getContentResolver();
3644        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3645        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3646        String exclList = Settings.Global.getString(res,
3647                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3648        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3649        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3650            ProxyInfo proxyProperties;
3651            if (!TextUtils.isEmpty(pacFileUrl)) {
3652                proxyProperties = new ProxyInfo(pacFileUrl);
3653            } else {
3654                proxyProperties = new ProxyInfo(host, port, exclList);
3655            }
3656            if (!proxyProperties.isValid()) {
3657                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3658                return;
3659            }
3660
3661            synchronized (mProxyLock) {
3662                mGlobalProxy = proxyProperties;
3663            }
3664        }
3665    }
3666
3667    public ProxyInfo getGlobalProxy() {
3668        // this information is already available as a world read/writable jvm property
3669        // so this API change wouldn't have a benifit.  It also breaks the passing
3670        // of proxy info to all the JVMs.
3671        // enforceAccessPermission();
3672        synchronized (mProxyLock) {
3673            return mGlobalProxy;
3674        }
3675    }
3676
3677    private void handleApplyDefaultProxy(ProxyInfo proxy) {
3678        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3679                && (proxy.getPacFileUrl() == null)) {
3680            proxy = null;
3681        }
3682        synchronized (mProxyLock) {
3683            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3684            if (mDefaultProxy == proxy) return; // catches repeated nulls
3685            if (proxy != null &&  !proxy.isValid()) {
3686                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3687                return;
3688            }
3689
3690            // This call could be coming from the PacManager, containing the port of the local
3691            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
3692            // global (to get the correct local port), and send a broadcast.
3693            // TODO: Switch PacManager to have its own message to send back rather than
3694            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
3695            if ((mGlobalProxy != null) && (proxy != null) && (proxy.getPacFileUrl() != null)
3696                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3697                mGlobalProxy = proxy;
3698                sendProxyBroadcast(mGlobalProxy);
3699                return;
3700            }
3701            mDefaultProxy = proxy;
3702
3703            if (mGlobalProxy != null) return;
3704            if (!mDefaultProxyDisabled) {
3705                sendProxyBroadcast(proxy);
3706            }
3707        }
3708    }
3709
3710    private void handleDeprecatedGlobalHttpProxy() {
3711        String proxy = Settings.Global.getString(mContext.getContentResolver(),
3712                Settings.Global.HTTP_PROXY);
3713        if (!TextUtils.isEmpty(proxy)) {
3714            String data[] = proxy.split(":");
3715            if (data.length == 0) {
3716                return;
3717            }
3718
3719            String proxyHost =  data[0];
3720            int proxyPort = 8080;
3721            if (data.length > 1) {
3722                try {
3723                    proxyPort = Integer.parseInt(data[1]);
3724                } catch (NumberFormatException e) {
3725                    return;
3726                }
3727            }
3728            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
3729            setGlobalProxy(p);
3730        }
3731    }
3732
3733    private void sendProxyBroadcast(ProxyInfo proxy) {
3734        if (proxy == null) proxy = new ProxyInfo("", 0, "");
3735        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
3736        if (DBG) log("sending Proxy Broadcast for " + proxy);
3737        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3738        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3739            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3740        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3741        final long ident = Binder.clearCallingIdentity();
3742        try {
3743            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3744        } finally {
3745            Binder.restoreCallingIdentity(ident);
3746        }
3747    }
3748
3749    private static class SettingsObserver extends ContentObserver {
3750        private int mWhat;
3751        private Handler mHandler;
3752        SettingsObserver(Handler handler, int what) {
3753            super(handler);
3754            mHandler = handler;
3755            mWhat = what;
3756        }
3757
3758        void observe(Context context) {
3759            ContentResolver resolver = context.getContentResolver();
3760            resolver.registerContentObserver(Settings.Global.getUriFor(
3761                    Settings.Global.HTTP_PROXY), false, this);
3762        }
3763
3764        @Override
3765        public void onChange(boolean selfChange) {
3766            mHandler.obtainMessage(mWhat).sendToTarget();
3767        }
3768    }
3769
3770    private static void log(String s) {
3771        Slog.d(TAG, s);
3772    }
3773
3774    private static void loge(String s) {
3775        Slog.e(TAG, s);
3776    }
3777
3778    int convertFeatureToNetworkType(int networkType, String feature) {
3779        int usedNetworkType = networkType;
3780
3781        if(networkType == ConnectivityManager.TYPE_MOBILE) {
3782            if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3783                usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3784            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3785                usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3786            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3787                    TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3788                usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3789            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3790                usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3791            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3792                usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3793            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3794                usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3795            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3796                usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3797            } else {
3798                Slog.e(TAG, "Can't match any mobile netTracker!");
3799            }
3800        } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3801            if (TextUtils.equals(feature, "p2p")) {
3802                usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3803            } else {
3804                Slog.e(TAG, "Can't match any wifi netTracker!");
3805            }
3806        } else {
3807            Slog.e(TAG, "Unexpected network type");
3808        }
3809        return usedNetworkType;
3810    }
3811
3812    private static <T> T checkNotNull(T value, String message) {
3813        if (value == null) {
3814            throw new NullPointerException(message);
3815        }
3816        return value;
3817    }
3818
3819    /**
3820     * Protect a socket from VPN routing rules. This method is used by
3821     * VpnBuilder and not available in ConnectivityManager. Permissions
3822     * are checked in Vpn class.
3823     * @hide
3824     */
3825    @Override
3826    public boolean protectVpn(ParcelFileDescriptor socket) {
3827        throwIfLockdownEnabled();
3828        try {
3829            int type = mActiveDefaultNetwork;
3830            int user = UserHandle.getUserId(Binder.getCallingUid());
3831            if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
3832                synchronized(mVpns) {
3833                    mVpns.get(user).protect(socket);
3834                }
3835                return true;
3836            }
3837        } catch (Exception e) {
3838            // ignore
3839        } finally {
3840            try {
3841                socket.close();
3842            } catch (Exception e) {
3843                // ignore
3844            }
3845        }
3846        return false;
3847    }
3848
3849    /**
3850     * Prepare for a VPN application. This method is used by VpnDialogs
3851     * and not available in ConnectivityManager. Permissions are checked
3852     * in Vpn class.
3853     * @hide
3854     */
3855    @Override
3856    public boolean prepareVpn(String oldPackage, String newPackage) {
3857        throwIfLockdownEnabled();
3858        int user = UserHandle.getUserId(Binder.getCallingUid());
3859        synchronized(mVpns) {
3860            return mVpns.get(user).prepare(oldPackage, newPackage);
3861        }
3862    }
3863
3864    @Override
3865    public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3866        enforceMarkNetworkSocketPermission();
3867        final long token = Binder.clearCallingIdentity();
3868        try {
3869            int mark = mNetd.getMarkForUid(uid);
3870            // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
3871            if (mark == -1) {
3872                mark = 0;
3873            }
3874            NetworkUtils.markSocket(socket.getFd(), mark);
3875        } catch (RemoteException e) {
3876        } finally {
3877            Binder.restoreCallingIdentity(token);
3878        }
3879    }
3880
3881    /**
3882     * Configure a TUN interface and return its file descriptor. Parameters
3883     * are encoded and opaque to this class. This method is used by VpnBuilder
3884     * and not available in ConnectivityManager. Permissions are checked in
3885     * Vpn class.
3886     * @hide
3887     */
3888    @Override
3889    public ParcelFileDescriptor establishVpn(VpnConfig config) {
3890        throwIfLockdownEnabled();
3891        int user = UserHandle.getUserId(Binder.getCallingUid());
3892        synchronized(mVpns) {
3893            return mVpns.get(user).establish(config);
3894        }
3895    }
3896
3897    /**
3898     * Start legacy VPN, controlling native daemons as needed. Creates a
3899     * secondary thread to perform connection work, returning quickly.
3900     */
3901    @Override
3902    public void startLegacyVpn(VpnProfile profile) {
3903        throwIfLockdownEnabled();
3904        final LinkProperties egress = getActiveLinkProperties();
3905        if (egress == null) {
3906            throw new IllegalStateException("Missing active network connection");
3907        }
3908        int user = UserHandle.getUserId(Binder.getCallingUid());
3909        synchronized(mVpns) {
3910            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3911        }
3912    }
3913
3914    /**
3915     * Return the information of the ongoing legacy VPN. This method is used
3916     * by VpnSettings and not available in ConnectivityManager. Permissions
3917     * are checked in Vpn class.
3918     * @hide
3919     */
3920    @Override
3921    public LegacyVpnInfo getLegacyVpnInfo() {
3922        throwIfLockdownEnabled();
3923        int user = UserHandle.getUserId(Binder.getCallingUid());
3924        synchronized(mVpns) {
3925            return mVpns.get(user).getLegacyVpnInfo();
3926        }
3927    }
3928
3929    /**
3930     * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3931     * not available in ConnectivityManager.
3932     * Permissions are checked in Vpn class.
3933     * @hide
3934     */
3935    @Override
3936    public VpnConfig getVpnConfig() {
3937        int user = UserHandle.getUserId(Binder.getCallingUid());
3938        synchronized(mVpns) {
3939            return mVpns.get(user).getVpnConfig();
3940        }
3941    }
3942
3943    /**
3944     * Callback for VPN subsystem. Currently VPN is not adapted to the service
3945     * through NetworkStateTracker since it works differently. For example, it
3946     * needs to override DNS servers but never takes the default routes. It
3947     * relies on another data network, and it could keep existing connections
3948     * alive after reconnecting, switching between networks, or even resuming
3949     * from deep sleep. Calls from applications should be done synchronously
3950     * to avoid race conditions. As these are all hidden APIs, refactoring can
3951     * be done whenever a better abstraction is developed.
3952     */
3953    public class VpnCallback {
3954        private VpnCallback() {
3955        }
3956
3957        public void onStateChanged(NetworkInfo info) {
3958            mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
3959        }
3960
3961        public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
3962            if (dnsServers == null) {
3963                restore();
3964                return;
3965            }
3966
3967            // Convert DNS servers into addresses.
3968            List<InetAddress> addresses = new ArrayList<InetAddress>();
3969            for (String address : dnsServers) {
3970                // Double check the addresses and remove invalid ones.
3971                try {
3972                    addresses.add(InetAddress.parseNumericAddress(address));
3973                } catch (Exception e) {
3974                    // ignore
3975                }
3976            }
3977            if (addresses.isEmpty()) {
3978                restore();
3979                return;
3980            }
3981
3982            // Concatenate search domains into a string.
3983            StringBuilder buffer = new StringBuilder();
3984            if (searchDomains != null) {
3985                for (String domain : searchDomains) {
3986                    buffer.append(domain).append(' ');
3987                }
3988            }
3989            String domains = buffer.toString().trim();
3990
3991            // Apply DNS changes.
3992            synchronized (mDnsLock) {
3993                // TODO: Re-enable this when the netId of the VPN is known.
3994                // updateDnsLocked("VPN", netId, addresses, domains);
3995            }
3996
3997            // Temporarily disable the default proxy (not global).
3998            synchronized (mProxyLock) {
3999                mDefaultProxyDisabled = true;
4000                if (mGlobalProxy == null && mDefaultProxy != null) {
4001                    sendProxyBroadcast(null);
4002                }
4003            }
4004
4005            // TODO: support proxy per network.
4006        }
4007
4008        public void restore() {
4009            synchronized (mProxyLock) {
4010                mDefaultProxyDisabled = false;
4011                if (mGlobalProxy == null && mDefaultProxy != null) {
4012                    sendProxyBroadcast(mDefaultProxy);
4013                }
4014            }
4015        }
4016
4017        public void protect(ParcelFileDescriptor socket) {
4018            try {
4019                final int mark = mNetd.getMarkForProtect();
4020                NetworkUtils.markSocket(socket.getFd(), mark);
4021            } catch (RemoteException e) {
4022            }
4023        }
4024
4025        public void setRoutes(String interfaze, List<RouteInfo> routes) {
4026            for (RouteInfo route : routes) {
4027                try {
4028                    mNetd.setMarkedForwardingRoute(interfaze, route);
4029                } catch (RemoteException e) {
4030                }
4031            }
4032        }
4033
4034        public void setMarkedForwarding(String interfaze) {
4035            try {
4036                mNetd.setMarkedForwarding(interfaze);
4037            } catch (RemoteException e) {
4038            }
4039        }
4040
4041        public void clearMarkedForwarding(String interfaze) {
4042            try {
4043                mNetd.clearMarkedForwarding(interfaze);
4044            } catch (RemoteException e) {
4045            }
4046        }
4047
4048        public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
4049            int uidStart = uid * UserHandle.PER_USER_RANGE;
4050            int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
4051            addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
4052        }
4053
4054        public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
4055            int uidStart = uid * UserHandle.PER_USER_RANGE;
4056            int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
4057            clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
4058        }
4059
4060        public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
4061                boolean forwardDns) {
4062            // TODO: Re-enable this when the netId of the VPN is known.
4063            // try {
4064            //     mNetd.setUidRangeRoute(netId, uidStart, uidEnd, forwardDns);
4065            // } catch (RemoteException e) {
4066            // }
4067
4068        }
4069
4070        public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
4071                boolean forwardDns) {
4072            // TODO: Re-enable this when the netId of the VPN is known.
4073            // try {
4074            //     mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
4075            // } catch (RemoteException e) {
4076            // }
4077
4078        }
4079    }
4080
4081    @Override
4082    public boolean updateLockdownVpn() {
4083        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4084            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4085            return false;
4086        }
4087
4088        // Tear down existing lockdown if profile was removed
4089        mLockdownEnabled = LockdownVpnTracker.isEnabled();
4090        if (mLockdownEnabled) {
4091            if (!mKeyStore.isUnlocked()) {
4092                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
4093                return false;
4094            }
4095
4096            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
4097            final VpnProfile profile = VpnProfile.decode(
4098                    profileName, mKeyStore.get(Credentials.VPN + profileName));
4099            int user = UserHandle.getUserId(Binder.getCallingUid());
4100            synchronized(mVpns) {
4101                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
4102                            profile));
4103            }
4104        } else {
4105            setLockdownTracker(null);
4106        }
4107
4108        return true;
4109    }
4110
4111    /**
4112     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4113     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4114     */
4115    private void setLockdownTracker(LockdownVpnTracker tracker) {
4116        // Shutdown any existing tracker
4117        final LockdownVpnTracker existing = mLockdownTracker;
4118        mLockdownTracker = null;
4119        if (existing != null) {
4120            existing.shutdown();
4121        }
4122
4123        try {
4124            if (tracker != null) {
4125                mNetd.setFirewallEnabled(true);
4126                mNetd.setFirewallInterfaceRule("lo", true);
4127                mLockdownTracker = tracker;
4128                mLockdownTracker.init();
4129            } else {
4130                mNetd.setFirewallEnabled(false);
4131            }
4132        } catch (RemoteException e) {
4133            // ignored; NMS lives inside system_server
4134        }
4135    }
4136
4137    private void throwIfLockdownEnabled() {
4138        if (mLockdownEnabled) {
4139            throw new IllegalStateException("Unavailable in lockdown mode");
4140        }
4141    }
4142
4143    public void supplyMessenger(int networkType, Messenger messenger) {
4144        enforceConnectivityInternalPermission();
4145
4146        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
4147            mNetTrackers[networkType].supplyMessenger(messenger);
4148        }
4149    }
4150
4151    public int findConnectionTypeForIface(String iface) {
4152        enforceConnectivityInternalPermission();
4153
4154        if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
4155        for (NetworkStateTracker tracker : mNetTrackers) {
4156            if (tracker != null) {
4157                LinkProperties lp = tracker.getLinkProperties();
4158                if (lp != null && iface.equals(lp.getInterfaceName())) {
4159                    return tracker.getNetworkInfo().getType();
4160                }
4161            }
4162        }
4163        return ConnectivityManager.TYPE_NONE;
4164    }
4165
4166    /**
4167     * Have mobile data fail fast if enabled.
4168     *
4169     * @param enabled DctConstants.ENABLED/DISABLED
4170     */
4171    private void setEnableFailFastMobileData(int enabled) {
4172        int tag;
4173
4174        if (enabled == DctConstants.ENABLED) {
4175            tag = mEnableFailFastMobileDataTag.incrementAndGet();
4176        } else {
4177            tag = mEnableFailFastMobileDataTag.get();
4178        }
4179        mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
4180                         enabled));
4181    }
4182
4183    private boolean isMobileDataStateTrackerReady() {
4184        MobileDataStateTracker mdst =
4185                (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4186        return (mdst != null) && (mdst.isReady());
4187    }
4188
4189    /**
4190     * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
4191     */
4192
4193    /**
4194     * No connection was possible to the network.
4195     * This is NOT a warm sim.
4196     */
4197    private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
4198
4199    /**
4200     * A connection was made to the internet, all is well.
4201     * This is NOT a warm sim.
4202     */
4203    private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
4204
4205    /**
4206     * A connection was made but no dns server was available to resolve a name to address.
4207     * This is NOT a warm sim since provisioning network is supported.
4208     */
4209    private static final int CMP_RESULT_CODE_NO_DNS = 2;
4210
4211    /**
4212     * A connection was made but could not open a TCP connection.
4213     * This is NOT a warm sim since provisioning network is supported.
4214     */
4215    private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
4216
4217    /**
4218     * A connection was made but there was a redirection, we appear to be in walled garden.
4219     * This is an indication of a warm sim on a mobile network such as T-Mobile.
4220     */
4221    private static final int CMP_RESULT_CODE_REDIRECTED = 4;
4222
4223    /**
4224     * The mobile network is a provisioning network.
4225     * This is an indication of a warm sim on a mobile network such as AT&T.
4226     */
4227    private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
4228
4229    /**
4230     * The mobile network is provisioning
4231     */
4232    private static final int CMP_RESULT_CODE_IS_PROVISIONING = 6;
4233
4234    private AtomicBoolean mIsProvisioningNetwork = new AtomicBoolean(false);
4235    private AtomicBoolean mIsStartingProvisioning = new AtomicBoolean(false);
4236
4237    private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
4238
4239    @Override
4240    public int checkMobileProvisioning(int suggestedTimeOutMs) {
4241        int timeOutMs = -1;
4242        if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
4243        enforceConnectivityInternalPermission();
4244
4245        final long token = Binder.clearCallingIdentity();
4246        try {
4247            timeOutMs = suggestedTimeOutMs;
4248            if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
4249                timeOutMs = CheckMp.MAX_TIMEOUT_MS;
4250            }
4251
4252            // Check that mobile networks are supported
4253            if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
4254                    || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
4255                if (DBG) log("checkMobileProvisioning: X no mobile network");
4256                return timeOutMs;
4257            }
4258
4259            // If we're already checking don't do it again
4260            // TODO: Add a queue of results...
4261            if (mIsCheckingMobileProvisioning.getAndSet(true)) {
4262                if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
4263                return timeOutMs;
4264            }
4265
4266            // Start off with mobile notification off
4267            setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
4268
4269            CheckMp checkMp = new CheckMp(mContext, this);
4270            CheckMp.CallBack cb = new CheckMp.CallBack() {
4271                @Override
4272                void onComplete(Integer result) {
4273                    if (DBG) log("CheckMp.onComplete: result=" + result);
4274                    NetworkInfo ni =
4275                            mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4276                    switch(result) {
4277                        case CMP_RESULT_CODE_CONNECTABLE:
4278                        case CMP_RESULT_CODE_NO_CONNECTION:
4279                        case CMP_RESULT_CODE_NO_DNS:
4280                        case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
4281                            if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
4282                            break;
4283                        }
4284                        case CMP_RESULT_CODE_REDIRECTED: {
4285                            if (DBG) log("CheckMp.onComplete: warm sim");
4286                            String url = getMobileProvisioningUrl();
4287                            if (TextUtils.isEmpty(url)) {
4288                                url = getMobileRedirectedProvisioningUrl();
4289                            }
4290                            if (TextUtils.isEmpty(url) == false) {
4291                                if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
4292                                setProvNotificationVisible(true,
4293                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
4294                                        url);
4295                            } else {
4296                                if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
4297                            }
4298                            break;
4299                        }
4300                        case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
4301                            String url = getMobileProvisioningUrl();
4302                            if (TextUtils.isEmpty(url) == false) {
4303                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
4304                                setProvNotificationVisible(true,
4305                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
4306                                        url);
4307                                // Mark that we've got a provisioning network and
4308                                // Disable Mobile Data until user actually starts provisioning.
4309                                mIsProvisioningNetwork.set(true);
4310                                MobileDataStateTracker mdst = (MobileDataStateTracker)
4311                                        mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4312                                mdst.setInternalDataEnable(false);
4313                            } else {
4314                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
4315                            }
4316                            break;
4317                        }
4318                        case CMP_RESULT_CODE_IS_PROVISIONING: {
4319                            // FIXME: Need to know when provisioning is done. Probably we can
4320                            // check the completion status if successful we're done if we
4321                            // "timedout" or still connected to provisioning APN turn off data?
4322                            if (DBG) log("CheckMp.onComplete: provisioning started");
4323                            mIsStartingProvisioning.set(false);
4324                            break;
4325                        }
4326                        default: {
4327                            loge("CheckMp.onComplete: ignore unexpected result=" + result);
4328                            break;
4329                        }
4330                    }
4331                    mIsCheckingMobileProvisioning.set(false);
4332                }
4333            };
4334            CheckMp.Params params =
4335                    new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
4336            if (DBG) log("checkMobileProvisioning: params=" + params);
4337            // TODO: Reenable when calls to the now defunct
4338            //       MobileDataStateTracker.isProvisioningNetwork() are removed.
4339            //       This code should be moved to the Telephony code.
4340            // checkMp.execute(params);
4341        } finally {
4342            Binder.restoreCallingIdentity(token);
4343            if (DBG) log("checkMobileProvisioning: X");
4344        }
4345        return timeOutMs;
4346    }
4347
4348    static class CheckMp extends
4349            AsyncTask<CheckMp.Params, Void, Integer> {
4350        private static final String CHECKMP_TAG = "CheckMp";
4351
4352        // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
4353        private static boolean mTestingFailures;
4354
4355        // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
4356        private static final int MAX_LOOPS = 4;
4357
4358        // Number of milli-seconds to complete all of the retires
4359        public static final int MAX_TIMEOUT_MS =  60000;
4360
4361        // The socket should retry only 5 seconds, the default is longer
4362        private static final int SOCKET_TIMEOUT_MS = 5000;
4363
4364        // Sleep time for network errors
4365        private static final int NET_ERROR_SLEEP_SEC = 3;
4366
4367        // Sleep time for network route establishment
4368        private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
4369
4370        // Short sleep time for polling :(
4371        private static final int POLLING_SLEEP_SEC = 1;
4372
4373        private Context mContext;
4374        private ConnectivityService mCs;
4375        private TelephonyManager mTm;
4376        private Params mParams;
4377
4378        /**
4379         * Parameters for AsyncTask.execute
4380         */
4381        static class Params {
4382            private String mUrl;
4383            private long mTimeOutMs;
4384            private CallBack mCb;
4385
4386            Params(String url, long timeOutMs, CallBack cb) {
4387                mUrl = url;
4388                mTimeOutMs = timeOutMs;
4389                mCb = cb;
4390            }
4391
4392            @Override
4393            public String toString() {
4394                return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4395            }
4396        }
4397
4398        // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
4399        // issued by name or ip address, for Google its by name so when we construct
4400        // this HostnameVerifier we'll pass the original Uri and use it to verify
4401        // the host. If the host name in the original uril fails we'll test the
4402        // hostname parameter just incase things change.
4403        static class CheckMpHostnameVerifier implements HostnameVerifier {
4404            Uri mOrgUri;
4405
4406            CheckMpHostnameVerifier(Uri orgUri) {
4407                mOrgUri = orgUri;
4408            }
4409
4410            @Override
4411            public boolean verify(String hostname, SSLSession session) {
4412                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
4413                String orgUriHost = mOrgUri.getHost();
4414                boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
4415                if (DBG) {
4416                    log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
4417                        + " orgUriHost=" + orgUriHost);
4418                }
4419                return retVal;
4420            }
4421        }
4422
4423        /**
4424         * The call back object passed in Params. onComplete will be called
4425         * on the main thread.
4426         */
4427        abstract static class CallBack {
4428            // Called on the main thread.
4429            abstract void onComplete(Integer result);
4430        }
4431
4432        public CheckMp(Context context, ConnectivityService cs) {
4433            if (Build.IS_DEBUGGABLE) {
4434                mTestingFailures =
4435                        SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
4436            } else {
4437                mTestingFailures = false;
4438            }
4439
4440            mContext = context;
4441            mCs = cs;
4442
4443            // Setup access to TelephonyService we'll be using.
4444            mTm = (TelephonyManager) mContext.getSystemService(
4445                    Context.TELEPHONY_SERVICE);
4446        }
4447
4448        /**
4449         * Get the default url to use for the test.
4450         */
4451        public String getDefaultUrl() {
4452            // See http://go/clientsdns for usage approval
4453            String server = Settings.Global.getString(mContext.getContentResolver(),
4454                    Settings.Global.CAPTIVE_PORTAL_SERVER);
4455            if (server == null) {
4456                server = "clients3.google.com";
4457            }
4458            return "http://" + server + "/generate_204";
4459        }
4460
4461        /**
4462         * Detect if its possible to connect to the http url. DNS based detection techniques
4463         * do not work at all hotspots. The best way to check is to perform a request to
4464         * a known address that fetches the data we expect.
4465         */
4466        private synchronized Integer isMobileOk(Params params) {
4467            Integer result = CMP_RESULT_CODE_NO_CONNECTION;
4468            Uri orgUri = Uri.parse(params.mUrl);
4469            Random rand = new Random();
4470            mParams = params;
4471
4472            if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
4473                result = CMP_RESULT_CODE_NO_CONNECTION;
4474                log("isMobileOk: X not mobile capable result=" + result);
4475                return result;
4476            }
4477
4478            if (mCs.mIsStartingProvisioning.get()) {
4479                result = CMP_RESULT_CODE_IS_PROVISIONING;
4480                log("isMobileOk: X is provisioning result=" + result);
4481                return result;
4482            }
4483
4484            // See if we've already determined we've got a provisioning connection,
4485            // if so we don't need to do anything active.
4486            MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4487                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4488            boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4489            log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4490
4491            MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4492                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4493            boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4494            log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4495
4496            if (isDefaultProvisioning || isHipriProvisioning) {
4497                result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4498                log("isMobileOk: X default || hipri is provisioning result=" + result);
4499                return result;
4500            }
4501
4502            try {
4503                // Continue trying to connect until time has run out
4504                long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
4505
4506                if (!mCs.isMobileDataStateTrackerReady()) {
4507                    // Wait for MobileDataStateTracker to be ready.
4508                    if (DBG) log("isMobileOk: mdst is not ready");
4509                    while(SystemClock.elapsedRealtime() < endTime) {
4510                        if (mCs.isMobileDataStateTrackerReady()) {
4511                            // Enable fail fast as we'll do retries here and use a
4512                            // hipri connection so the default connection stays active.
4513                            if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4514                            mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4515                            break;
4516                        }
4517                        sleep(POLLING_SLEEP_SEC);
4518                    }
4519                }
4520
4521                log("isMobileOk: start hipri url=" + params.mUrl);
4522
4523                // First wait until we can start using hipri
4524                Binder binder = new Binder();
4525                while(SystemClock.elapsedRealtime() < endTime) {
4526                    int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4527                            Phone.FEATURE_ENABLE_HIPRI, binder);
4528                    if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4529                        || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4530                            log("isMobileOk: hipri started");
4531                            break;
4532                    }
4533                    if (VDBG) log("isMobileOk: hipri not started yet");
4534                    result = CMP_RESULT_CODE_NO_CONNECTION;
4535                    sleep(POLLING_SLEEP_SEC);
4536                }
4537
4538                // Continue trying to connect until time has run out
4539                while(SystemClock.elapsedRealtime() < endTime) {
4540                    try {
4541                        // Wait for hipri to connect.
4542                        // TODO: Don't poll and handle situation where hipri fails
4543                        // because default is retrying. See b/9569540
4544                        NetworkInfo.State state = mCs
4545                                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4546                        if (state != NetworkInfo.State.CONNECTED) {
4547                            if (true/*VDBG*/) {
4548                                log("isMobileOk: not connected ni=" +
4549                                    mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4550                            }
4551                            sleep(POLLING_SLEEP_SEC);
4552                            result = CMP_RESULT_CODE_NO_CONNECTION;
4553                            continue;
4554                        }
4555
4556                        // Hipri has started check if this is a provisioning url
4557                        MobileDataStateTracker mdst = (MobileDataStateTracker)
4558                                mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4559                        if (mdst.isProvisioningNetwork()) {
4560                            result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4561                            if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
4562                            return result;
4563                        } else {
4564                            if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4565                        }
4566
4567                        // Get of the addresses associated with the url host. We need to use the
4568                        // address otherwise HttpURLConnection object will use the name to get
4569                        // the addresses and will try every address but that will bypass the
4570                        // route to host we setup and the connection could succeed as the default
4571                        // interface might be connected to the internet via wifi or other interface.
4572                        InetAddress[] addresses;
4573                        try {
4574                            addresses = InetAddress.getAllByName(orgUri.getHost());
4575                        } catch (UnknownHostException e) {
4576                            result = CMP_RESULT_CODE_NO_DNS;
4577                            log("isMobileOk: X UnknownHostException result=" + result);
4578                            return result;
4579                        }
4580                        log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4581
4582                        // Get the type of addresses supported by this link
4583                        LinkProperties lp = mCs.getLinkPropertiesForTypeInternal(
4584                                ConnectivityManager.TYPE_MOBILE_HIPRI);
4585                        boolean linkHasIpv4 = lp.hasIPv4Address();
4586                        boolean linkHasIpv6 = lp.hasIPv6Address();
4587                        log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4588                                + " linkHasIpv6=" + linkHasIpv6);
4589
4590                        final ArrayList<InetAddress> validAddresses =
4591                                new ArrayList<InetAddress>(addresses.length);
4592
4593                        for (InetAddress addr : addresses) {
4594                            if (((addr instanceof Inet4Address) && linkHasIpv4) ||
4595                                    ((addr instanceof Inet6Address) && linkHasIpv6)) {
4596                                validAddresses.add(addr);
4597                            }
4598                        }
4599
4600                        if (validAddresses.size() == 0) {
4601                            return CMP_RESULT_CODE_NO_CONNECTION;
4602                        }
4603
4604                        int addrTried = 0;
4605                        while (true) {
4606                            // Loop through at most MAX_LOOPS valid addresses or until
4607                            // we run out of time
4608                            if (addrTried++ >= MAX_LOOPS) {
4609                                log("isMobileOk: too many loops tried - giving up");
4610                                break;
4611                            }
4612                            if (SystemClock.elapsedRealtime() >= endTime) {
4613                                log("isMobileOk: spend too much time - giving up");
4614                                break;
4615                            }
4616
4617                            InetAddress hostAddr = validAddresses.get(rand.nextInt(
4618                                    validAddresses.size()));
4619
4620                            // Make a route to host so we check the specific interface.
4621                            if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4622                                    hostAddr.getAddress(), null)) {
4623                                // Wait a short time to be sure the route is established ??
4624                                log("isMobileOk:"
4625                                        + " wait to establish route to hostAddr=" + hostAddr);
4626                                sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
4627                            } else {
4628                                log("isMobileOk:"
4629                                        + " could not establish route to hostAddr=" + hostAddr);
4630                                // Wait a short time before the next attempt
4631                                sleep(NET_ERROR_SLEEP_SEC);
4632                                continue;
4633                            }
4634
4635                            // Rewrite the url to have numeric address to use the specific route
4636                            // using http for half the attempts and https for the other half.
4637                            // Doing https first and http second as on a redirected walled garden
4638                            // such as t-mobile uses we get a SocketTimeoutException: "SSL
4639                            // handshake timed out" which we declare as
4640                            // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
4641                            // having http second we will be using logic used for some time.
4642                            URL newUrl;
4643                            String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
4644                            newUrl = new URL(scheme, hostAddr.getHostAddress(),
4645                                        orgUri.getPath());
4646                            log("isMobileOk: newUrl=" + newUrl);
4647
4648                            HttpURLConnection urlConn = null;
4649                            try {
4650                                // Open the connection set the request headers and get the response
4651                                urlConn = (HttpURLConnection)newUrl.openConnection(
4652                                        java.net.Proxy.NO_PROXY);
4653                                if (scheme.equals("https")) {
4654                                    ((HttpsURLConnection)urlConn).setHostnameVerifier(
4655                                            new CheckMpHostnameVerifier(orgUri));
4656                                }
4657                                urlConn.setInstanceFollowRedirects(false);
4658                                urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4659                                urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4660                                urlConn.setUseCaches(false);
4661                                urlConn.setAllowUserInteraction(false);
4662                                // Set the "Connection" to "Close" as by default "Keep-Alive"
4663                                // is used which is useless in this case.
4664                                urlConn.setRequestProperty("Connection", "close");
4665                                int responseCode = urlConn.getResponseCode();
4666
4667                                // For debug display the headers
4668                                Map<String, List<String>> headers = urlConn.getHeaderFields();
4669                                log("isMobileOk: headers=" + headers);
4670
4671                                // Close the connection
4672                                urlConn.disconnect();
4673                                urlConn = null;
4674
4675                                if (mTestingFailures) {
4676                                    // Pretend no connection, this tests using http and https
4677                                    result = CMP_RESULT_CODE_NO_CONNECTION;
4678                                    log("isMobileOk: TESTING_FAILURES, pretend no connction");
4679                                    continue;
4680                                }
4681
4682                                if (responseCode == 204) {
4683                                    // Return
4684                                    result = CMP_RESULT_CODE_CONNECTABLE;
4685                                    log("isMobileOk: X got expected responseCode=" + responseCode
4686                                            + " result=" + result);
4687                                    return result;
4688                                } else {
4689                                    // Retry to be sure this was redirected, we've gotten
4690                                    // occasions where a server returned 200 even though
4691                                    // the device didn't have a "warm" sim.
4692                                    log("isMobileOk: not expected responseCode=" + responseCode);
4693                                    // TODO - it would be nice in the single-address case to do
4694                                    // another DNS resolve here, but flushing the cache is a bit
4695                                    // heavy-handed.
4696                                    result = CMP_RESULT_CODE_REDIRECTED;
4697                                }
4698                            } catch (Exception e) {
4699                                log("isMobileOk: HttpURLConnection Exception" + e);
4700                                result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
4701                                if (urlConn != null) {
4702                                    urlConn.disconnect();
4703                                    urlConn = null;
4704                                }
4705                                sleep(NET_ERROR_SLEEP_SEC);
4706                                continue;
4707                            }
4708                        }
4709                        log("isMobileOk: X loops|timed out result=" + result);
4710                        return result;
4711                    } catch (Exception e) {
4712                        log("isMobileOk: Exception e=" + e);
4713                        continue;
4714                    }
4715                }
4716                log("isMobileOk: timed out");
4717            } finally {
4718                log("isMobileOk: F stop hipri");
4719                mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4720                mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4721                        Phone.FEATURE_ENABLE_HIPRI);
4722
4723                // Wait for hipri to disconnect.
4724                long endTime = SystemClock.elapsedRealtime() + 5000;
4725
4726                while(SystemClock.elapsedRealtime() < endTime) {
4727                    NetworkInfo.State state = mCs
4728                            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4729                    if (state != NetworkInfo.State.DISCONNECTED) {
4730                        if (VDBG) {
4731                            log("isMobileOk: connected ni=" +
4732                                mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4733                        }
4734                        sleep(POLLING_SLEEP_SEC);
4735                        continue;
4736                    }
4737                }
4738
4739                log("isMobileOk: X result=" + result);
4740            }
4741            return result;
4742        }
4743
4744        @Override
4745        protected Integer doInBackground(Params... params) {
4746            return isMobileOk(params[0]);
4747        }
4748
4749        @Override
4750        protected void onPostExecute(Integer result) {
4751            log("onPostExecute: result=" + result);
4752            if ((mParams != null) && (mParams.mCb != null)) {
4753                mParams.mCb.onComplete(result);
4754            }
4755        }
4756
4757        private String inetAddressesToString(InetAddress[] addresses) {
4758            StringBuffer sb = new StringBuffer();
4759            boolean firstTime = true;
4760            for(InetAddress addr : addresses) {
4761                if (firstTime) {
4762                    firstTime = false;
4763                } else {
4764                    sb.append(",");
4765                }
4766                sb.append(addr);
4767            }
4768            return sb.toString();
4769        }
4770
4771        private void printNetworkInfo() {
4772            boolean hasIccCard = mTm.hasIccCard();
4773            int simState = mTm.getSimState();
4774            log("hasIccCard=" + hasIccCard
4775                    + " simState=" + simState);
4776            NetworkInfo[] ni = mCs.getAllNetworkInfo();
4777            if (ni != null) {
4778                log("ni.length=" + ni.length);
4779                for (NetworkInfo netInfo: ni) {
4780                    log("netInfo=" + netInfo.toString());
4781                }
4782            } else {
4783                log("no network info ni=null");
4784            }
4785        }
4786
4787        /**
4788         * Sleep for a few seconds then return.
4789         * @param seconds
4790         */
4791        private static void sleep(int seconds) {
4792            long stopTime = System.nanoTime() + (seconds * 1000000000);
4793            long sleepTime;
4794            while ((sleepTime = stopTime - System.nanoTime()) > 0) {
4795                try {
4796                    Thread.sleep(sleepTime / 1000000);
4797                } catch (InterruptedException ignored) {
4798                }
4799            }
4800        }
4801
4802        private static void log(String s) {
4803            Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4804        }
4805    }
4806
4807    // TODO: Move to ConnectivityManager and make public?
4808    private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4809            "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
4810
4811    private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4812        @Override
4813        public void onReceive(Context context, Intent intent) {
4814            if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4815                handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4816            }
4817        }
4818    };
4819
4820    private void handleMobileProvisioningAction(String url) {
4821        // Mark notification as not visible
4822        setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
4823
4824        // If provisioning network handle as a special case,
4825        // otherwise launch browser with the intent directly.
4826        if (mIsProvisioningNetwork.get()) {
4827            if (DBG) log("handleMobileProvisioningAction: on prov network enable then launch");
4828//            mIsStartingProvisioning.set(true);
4829//            MobileDataStateTracker mdst = (MobileDataStateTracker)
4830//                    mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4831//            mdst.setEnableFailFastMobileData(DctConstants.ENABLED);
4832//            mdst.enableMobileProvisioning(url);
4833        } else {
4834            if (DBG) log("handleMobileProvisioningAction: not prov network");
4835            // Check for  apps that can handle provisioning first
4836            Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP);
4837            provisioningIntent.addCategory(TelephonyIntents.CATEGORY_MCCMNC_PREFIX
4838                    + mTelephonyManager.getSimOperator());
4839            if (mContext.getPackageManager().resolveActivity(provisioningIntent, 0 /* flags */)
4840                    != null) {
4841                provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4842                        Intent.FLAG_ACTIVITY_NEW_TASK);
4843                mContext.startActivity(provisioningIntent);
4844            } else {
4845                // If no apps exist, use standard URL ACTION_VIEW method
4846                Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
4847                        Intent.CATEGORY_APP_BROWSER);
4848                newIntent.setData(Uri.parse(url));
4849                newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4850                        Intent.FLAG_ACTIVITY_NEW_TASK);
4851                try {
4852                    mContext.startActivity(newIntent);
4853                } catch (ActivityNotFoundException e) {
4854                    loge("handleMobileProvisioningAction: startActivity failed" + e);
4855                }
4856            }
4857        }
4858    }
4859
4860    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4861    private volatile boolean mIsNotificationVisible = false;
4862
4863    private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4864            String url) {
4865        if (DBG) {
4866            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4867                + " extraInfo=" + extraInfo + " url=" + url);
4868        }
4869
4870        Resources r = Resources.getSystem();
4871        NotificationManager notificationManager = (NotificationManager) mContext
4872            .getSystemService(Context.NOTIFICATION_SERVICE);
4873
4874        if (visible) {
4875            CharSequence title;
4876            CharSequence details;
4877            int icon;
4878            Intent intent;
4879            Notification notification = new Notification();
4880            switch (networkType) {
4881                case ConnectivityManager.TYPE_WIFI:
4882                    title = r.getString(R.string.wifi_available_sign_in, 0);
4883                    details = r.getString(R.string.network_available_sign_in_detailed,
4884                            extraInfo);
4885                    icon = R.drawable.stat_notify_wifi_in_range;
4886                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4887                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4888                            Intent.FLAG_ACTIVITY_NEW_TASK);
4889                    notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4890                    break;
4891                case ConnectivityManager.TYPE_MOBILE:
4892                case ConnectivityManager.TYPE_MOBILE_HIPRI:
4893                    title = r.getString(R.string.network_available_sign_in, 0);
4894                    // TODO: Change this to pull from NetworkInfo once a printable
4895                    // name has been added to it
4896                    details = mTelephonyManager.getNetworkOperatorName();
4897                    icon = R.drawable.stat_notify_rssi_in_range;
4898                    intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
4899                    intent.putExtra("EXTRA_URL", url);
4900                    intent.setFlags(0);
4901                    notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
4902                    break;
4903                default:
4904                    title = r.getString(R.string.network_available_sign_in, 0);
4905                    details = r.getString(R.string.network_available_sign_in_detailed,
4906                            extraInfo);
4907                    icon = R.drawable.stat_notify_rssi_in_range;
4908                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
4909                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4910                            Intent.FLAG_ACTIVITY_NEW_TASK);
4911                    notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
4912                    break;
4913            }
4914
4915            notification.when = 0;
4916            notification.icon = icon;
4917            notification.flags = Notification.FLAG_AUTO_CANCEL;
4918            notification.tickerText = title;
4919            notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
4920
4921            try {
4922                notificationManager.notify(NOTIFICATION_ID, networkType, notification);
4923            } catch (NullPointerException npe) {
4924                loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
4925                npe.printStackTrace();
4926            }
4927        } else {
4928            try {
4929                notificationManager.cancel(NOTIFICATION_ID, networkType);
4930            } catch (NullPointerException npe) {
4931                loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
4932                npe.printStackTrace();
4933            }
4934        }
4935        mIsNotificationVisible = visible;
4936    }
4937
4938    /** Location to an updatable file listing carrier provisioning urls.
4939     *  An example:
4940     *
4941     * <?xml version="1.0" encoding="utf-8"?>
4942     *  <provisioningUrls>
4943     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
4944     *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
4945     *  </provisioningUrls>
4946     */
4947    private static final String PROVISIONING_URL_PATH =
4948            "/data/misc/radio/provisioning_urls.xml";
4949    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
4950
4951    /** XML tag for root element. */
4952    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
4953    /** XML tag for individual url */
4954    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
4955    /** XML tag for redirected url */
4956    private static final String TAG_REDIRECTED_URL = "redirectedUrl";
4957    /** XML attribute for mcc */
4958    private static final String ATTR_MCC = "mcc";
4959    /** XML attribute for mnc */
4960    private static final String ATTR_MNC = "mnc";
4961
4962    private static final int REDIRECTED_PROVISIONING = 1;
4963    private static final int PROVISIONING = 2;
4964
4965    private String getProvisioningUrlBaseFromFile(int type) {
4966        FileReader fileReader = null;
4967        XmlPullParser parser = null;
4968        Configuration config = mContext.getResources().getConfiguration();
4969        String tagType;
4970
4971        switch (type) {
4972            case PROVISIONING:
4973                tagType = TAG_PROVISIONING_URL;
4974                break;
4975            case REDIRECTED_PROVISIONING:
4976                tagType = TAG_REDIRECTED_URL;
4977                break;
4978            default:
4979                throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
4980                        type);
4981        }
4982
4983        try {
4984            fileReader = new FileReader(mProvisioningUrlFile);
4985            parser = Xml.newPullParser();
4986            parser.setInput(fileReader);
4987            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
4988
4989            while (true) {
4990                XmlUtils.nextElement(parser);
4991
4992                String element = parser.getName();
4993                if (element == null) break;
4994
4995                if (element.equals(tagType)) {
4996                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
4997                    try {
4998                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
4999                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
5000                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
5001                                parser.next();
5002                                if (parser.getEventType() == XmlPullParser.TEXT) {
5003                                    return parser.getText();
5004                                }
5005                            }
5006                        }
5007                    } catch (NumberFormatException e) {
5008                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
5009                    }
5010                }
5011            }
5012            return null;
5013        } catch (FileNotFoundException e) {
5014            loge("Carrier Provisioning Urls file not found");
5015        } catch (XmlPullParserException e) {
5016            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
5017        } catch (IOException e) {
5018            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
5019        } finally {
5020            if (fileReader != null) {
5021                try {
5022                    fileReader.close();
5023                } catch (IOException e) {}
5024            }
5025        }
5026        return null;
5027    }
5028
5029    @Override
5030    public String getMobileRedirectedProvisioningUrl() {
5031        enforceConnectivityInternalPermission();
5032        String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
5033        if (TextUtils.isEmpty(url)) {
5034            url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
5035        }
5036        return url;
5037    }
5038
5039    @Override
5040    public String getMobileProvisioningUrl() {
5041        enforceConnectivityInternalPermission();
5042        String url = getProvisioningUrlBaseFromFile(PROVISIONING);
5043        if (TextUtils.isEmpty(url)) {
5044            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
5045            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
5046        } else {
5047            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
5048        }
5049        // populate the iccid, imei and phone number in the provisioning url.
5050        if (!TextUtils.isEmpty(url)) {
5051            String phoneNumber = mTelephonyManager.getLine1Number();
5052            if (TextUtils.isEmpty(phoneNumber)) {
5053                phoneNumber = "0000000000";
5054            }
5055            url = String.format(url,
5056                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
5057                    mTelephonyManager.getDeviceId() /* IMEI */,
5058                    phoneNumber /* Phone numer */);
5059        }
5060
5061        return url;
5062    }
5063
5064    @Override
5065    public void setProvisioningNotificationVisible(boolean visible, int networkType,
5066            String extraInfo, String url) {
5067        enforceConnectivityInternalPermission();
5068        setProvNotificationVisible(visible, networkType, extraInfo, url);
5069    }
5070
5071    @Override
5072    public void setAirplaneMode(boolean enable) {
5073        enforceConnectivityInternalPermission();
5074        final long ident = Binder.clearCallingIdentity();
5075        try {
5076            final ContentResolver cr = mContext.getContentResolver();
5077            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
5078            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5079            intent.putExtra("state", enable);
5080            mContext.sendBroadcast(intent);
5081        } finally {
5082            Binder.restoreCallingIdentity(ident);
5083        }
5084    }
5085
5086    private void onUserStart(int userId) {
5087        synchronized(mVpns) {
5088            Vpn userVpn = mVpns.get(userId);
5089            if (userVpn != null) {
5090                loge("Starting user already has a VPN");
5091                return;
5092            }
5093            userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
5094            mVpns.put(userId, userVpn);
5095            userVpn.startMonitoring(mContext, mTrackerHandler);
5096        }
5097    }
5098
5099    private void onUserStop(int userId) {
5100        synchronized(mVpns) {
5101            Vpn userVpn = mVpns.get(userId);
5102            if (userVpn == null) {
5103                loge("Stopping user has no VPN");
5104                return;
5105            }
5106            mVpns.delete(userId);
5107        }
5108    }
5109
5110    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
5111        @Override
5112        public void onReceive(Context context, Intent intent) {
5113            final String action = intent.getAction();
5114            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
5115            if (userId == UserHandle.USER_NULL) return;
5116
5117            if (Intent.ACTION_USER_STARTING.equals(action)) {
5118                onUserStart(userId);
5119            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
5120                onUserStop(userId);
5121            }
5122        }
5123    };
5124
5125    @Override
5126    public LinkQualityInfo getLinkQualityInfo(int networkType) {
5127        enforceAccessPermission();
5128        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
5129            return mNetTrackers[networkType].getLinkQualityInfo();
5130        } else {
5131            return null;
5132        }
5133    }
5134
5135    @Override
5136    public LinkQualityInfo getActiveLinkQualityInfo() {
5137        enforceAccessPermission();
5138        if (isNetworkTypeValid(mActiveDefaultNetwork) &&
5139                mNetTrackers[mActiveDefaultNetwork] != null) {
5140            return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
5141        } else {
5142            return null;
5143        }
5144    }
5145
5146    @Override
5147    public LinkQualityInfo[] getAllLinkQualityInfo() {
5148        enforceAccessPermission();
5149        final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
5150        for (NetworkStateTracker tracker : mNetTrackers) {
5151            if (tracker != null) {
5152                LinkQualityInfo li = tracker.getLinkQualityInfo();
5153                if (li != null) {
5154                    result.add(li);
5155                }
5156            }
5157        }
5158
5159        return result.toArray(new LinkQualityInfo[result.size()]);
5160    }
5161
5162    /* Infrastructure for network sampling */
5163
5164    private void handleNetworkSamplingTimeout() {
5165
5166        log("Sampling interval elapsed, updating statistics ..");
5167
5168        // initialize list of interfaces ..
5169        Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
5170                new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
5171        for (NetworkStateTracker tracker : mNetTrackers) {
5172            if (tracker != null) {
5173                String ifaceName = tracker.getNetworkInterfaceName();
5174                if (ifaceName != null) {
5175                    mapIfaceToSample.put(ifaceName, null);
5176                }
5177            }
5178        }
5179
5180        // Read samples for all interfaces
5181        SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
5182
5183        // process samples for all networks
5184        for (NetworkStateTracker tracker : mNetTrackers) {
5185            if (tracker != null) {
5186                String ifaceName = tracker.getNetworkInterfaceName();
5187                SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
5188                if (ss != null) {
5189                    // end the previous sampling cycle
5190                    tracker.stopSampling(ss);
5191                    // start a new sampling cycle ..
5192                    tracker.startSampling(ss);
5193                }
5194            }
5195        }
5196
5197        log("Done.");
5198
5199        int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
5200                Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
5201                DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
5202
5203        if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
5204
5205        setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
5206    }
5207
5208    void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
5209        long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
5210        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
5211    }
5212
5213    private final ArrayList<AsyncChannel> mNetworkFactories = new ArrayList<AsyncChannel>();
5214    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
5215            new HashMap<NetworkRequest, NetworkRequestInfo>();
5216
5217
5218    private class NetworkRequestInfo implements IBinder.DeathRecipient {
5219        static final boolean REQUEST = true;
5220        static final boolean LISTEN = false;
5221
5222        final NetworkRequest request;
5223        IBinder mBinder;
5224        final int mPid;
5225        final int mUid;
5226        final Messenger messenger;
5227        final boolean isRequest;
5228
5229        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
5230            super();
5231            messenger = m;
5232            request = r;
5233            mBinder = binder;
5234            mPid = getCallingPid();
5235            mUid = getCallingUid();
5236            this.isRequest = isRequest;
5237
5238            try {
5239                mBinder.linkToDeath(this, 0);
5240            } catch (RemoteException e) {
5241                binderDied();
5242            }
5243        }
5244
5245        void unlinkDeathRecipient() {
5246            mBinder.unlinkToDeath(this, 0);
5247        }
5248
5249        public void binderDied() {
5250            log("ConnectivityService NetworkRequestInfo binderDied(" +
5251                    request + ", " + mBinder + ")");
5252            releaseNetworkRequest(request);
5253        }
5254    }
5255
5256    @Override
5257    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
5258            Messenger messenger, int timeoutSec, IBinder binder) {
5259        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
5260                == false) {
5261            enforceConnectivityInternalPermission();
5262        } else {
5263            enforceChangePermission();
5264        }
5265
5266        if (timeoutSec < 0 || timeoutSec > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_SEC) {
5267            throw new IllegalArgumentException("Bad timeout specified");
5268        }
5269        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
5270                networkCapabilities));
5271        if (DBG) log("requestNetwork for " + networkRequest);
5272        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
5273                NetworkRequestInfo.REQUEST);
5274
5275        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
5276        if (timeoutSec > 0) {
5277            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
5278                    nri), timeoutSec * 1000);
5279        }
5280        return networkRequest;
5281    }
5282
5283    @Override
5284    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5285            PendingIntent operation) {
5286        // TODO
5287        return null;
5288    }
5289
5290    @Override
5291    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5292            Messenger messenger, IBinder binder) {
5293        enforceAccessPermission();
5294
5295        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
5296                networkCapabilities));
5297        if (DBG) log("listenForNetwork for " + networkRequest);
5298        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
5299                NetworkRequestInfo.LISTEN);
5300
5301        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5302        return networkRequest;
5303    }
5304
5305    @Override
5306    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5307            PendingIntent operation) {
5308    }
5309
5310    @Override
5311    public void releaseNetworkRequest(NetworkRequest networkRequest) {
5312        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST,
5313                networkRequest));
5314    }
5315
5316    @Override
5317    public void registerNetworkFactory(Messenger messenger) {
5318        enforceConnectivityInternalPermission();
5319        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, messenger));
5320    }
5321
5322    private void handleRegisterNetworkFactory(Messenger messenger) {
5323        if (VDBG) log("Got NetworkFactory Messenger");
5324        AsyncChannel ac = new AsyncChannel();
5325        mNetworkFactories.add(ac);
5326        ac.connect(mContext, mTrackerHandler, messenger);
5327        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5328            if (nri.isRequest) {
5329                int score = 0;
5330                NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
5331                if (currentNetwork != null) score = currentNetwork.currentScore;
5332                ac.sendMessage(NetworkFactoryProtocol.CMD_REQUEST_NETWORK, score, 0, nri.request);
5333            }
5334        }
5335    }
5336
5337    /**
5338     * NetworkAgentInfo supporting a request by requestId.
5339     * These have already been vetted (their Capabilities satisfy the request)
5340     * and the are the highest scored network available.
5341     * the are keyed off the Requests requestId.
5342     */
5343    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
5344            new SparseArray<NetworkAgentInfo>();
5345
5346    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
5347            new SparseArray<NetworkAgentInfo>();
5348
5349    // NetworkAgentInfo keyed off its connecting messenger
5350    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
5351    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
5352            new HashMap<Messenger, NetworkAgentInfo>();
5353
5354    private final NetworkRequest mDefaultRequest;
5355
5356    public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5357            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5358            int currentScore) {
5359        enforceConnectivityInternalPermission();
5360
5361        NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), nextNetId(),
5362            new NetworkInfo(networkInfo), new LinkProperties(linkProperties),
5363            new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler);
5364
5365        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
5366    }
5367
5368    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
5369        if (VDBG) log("Got NetworkAgent Messenger");
5370        mNetworkAgentInfos.put(na.messenger, na);
5371        try {
5372            mNetworkAgentInfoForType[na.networkInfo.getType()].add(na);
5373        } catch (NullPointerException e) {
5374            loge("registered NetworkAgent for unsupported type: " + na);
5375        }
5376        mNetworkForNetId.put(na.network.netId, na);
5377        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
5378        NetworkInfo networkInfo = na.networkInfo;
5379        na.networkInfo = null;
5380        updateNetworkInfo(na, networkInfo);
5381    }
5382
5383    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
5384        LinkProperties newLp = networkAgent.linkProperties;
5385        int netId = networkAgent.network.netId;
5386
5387        updateInterfaces(newLp, oldLp, netId);
5388        updateMtu(newLp, oldLp);
5389        // TODO - figure out what to do for clat
5390//        for (LinkProperties lp : newLp.getStackedLinks()) {
5391//            updateMtu(lp, null);
5392//        }
5393        updateRoutes(newLp, oldLp, netId);
5394        updateDnses(newLp, oldLp, netId);
5395        updateClat(newLp, oldLp, networkAgent);
5396    }
5397
5398    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo na) {
5399        // Update 464xlat state.
5400        if (mClat.requiresClat(na)) {
5401
5402            // If the connection was previously using clat, but is not using it now, stop the clat
5403            // daemon. Normally, this happens automatically when the connection disconnects, but if
5404            // the disconnect is not reported, or if the connection's LinkProperties changed for
5405            // some other reason (e.g., handoff changes the IP addresses on the link), it would
5406            // still be running. If it's not running, then stopping it is a no-op.
5407            if (Nat464Xlat.isRunningClat(oldLp) && !Nat464Xlat.isRunningClat(newLp)) {
5408                mClat.stopClat();
5409            }
5410            // If the link requires clat to be running, then start the daemon now.
5411            if (newLp != null && na.networkInfo.isConnected()) {
5412                mClat.startClat(na);
5413            } else {
5414                mClat.stopClat();
5415            }
5416        }
5417    }
5418
5419    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
5420        CompareResult<String> interfaceDiff = new CompareResult<String>();
5421        if (oldLp != null) {
5422            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
5423        } else if (newLp != null) {
5424            interfaceDiff.added = newLp.getAllInterfaceNames();
5425        }
5426        for (String iface : interfaceDiff.added) {
5427            try {
5428                mNetd.addInterfaceToNetwork(iface, netId);
5429            } catch (Exception e) {
5430                loge("Exception adding interface: " + e);
5431            }
5432        }
5433        for (String iface : interfaceDiff.removed) {
5434            try {
5435                mNetd.removeInterfaceFromNetwork(iface, netId);
5436            } catch (Exception e) {
5437                loge("Exception removing interface: " + e);
5438            }
5439        }
5440    }
5441
5442    private void updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
5443        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
5444        if (oldLp != null) {
5445            routeDiff = oldLp.compareAllRoutes(newLp);
5446        } else if (newLp != null) {
5447            routeDiff.added = newLp.getAllRoutes();
5448        }
5449
5450        // add routes before removing old in case it helps with continuous connectivity
5451
5452        // do this twice, adding non-nexthop routes first, then routes they are dependent on
5453        for (RouteInfo route : routeDiff.added) {
5454            if (route.hasGateway()) continue;
5455            try {
5456                mNetd.addRoute(netId, route);
5457            } catch (Exception e) {
5458                loge("Exception in addRoute for non-gateway: " + e);
5459            }
5460        }
5461        for (RouteInfo route : routeDiff.added) {
5462            if (route.hasGateway() == false) continue;
5463            try {
5464                mNetd.addRoute(netId, route);
5465            } catch (Exception e) {
5466                loge("Exception in addRoute for gateway: " + e);
5467            }
5468        }
5469
5470        for (RouteInfo route : routeDiff.removed) {
5471            try {
5472                mNetd.removeRoute(netId, route);
5473            } catch (Exception e) {
5474                loge("Exception in removeRoute: " + e);
5475            }
5476        }
5477    }
5478    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5479        if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
5480            Collection<InetAddress> dnses = newLp.getDnses();
5481            if (dnses.size() == 0 && mDefaultDns != null) {
5482                dnses = new ArrayList();
5483                dnses.add(mDefaultDns);
5484                if (DBG) {
5485                    loge("no dns provided for netId " + netId + ", so using defaults");
5486                }
5487            }
5488            try {
5489                mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
5490                    newLp.getDomains());
5491            } catch (Exception e) {
5492                loge("Exception in setDnsServersForNetwork: " + e);
5493            }
5494            NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
5495            if (defaultNai != null && defaultNai.network.netId == netId) {
5496                setDefaultDnsSystemProperties(dnses);
5497            }
5498        }
5499    }
5500
5501    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
5502        int last = 0;
5503        for (InetAddress dns : dnses) {
5504            ++last;
5505            String key = "net.dns" + last;
5506            String value = dns.getHostAddress();
5507            SystemProperties.set(key, value);
5508        }
5509        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
5510            String key = "net.dns" + i;
5511            SystemProperties.set(key, "");
5512        }
5513        mNumDnsEntries = last;
5514    }
5515
5516
5517    private void updateCapabilities(NetworkAgentInfo networkAgent,
5518            NetworkCapabilities networkCapabilities) {
5519        // TODO - what else here?  Verify still satisfies everybody?
5520        // Check if satisfies somebody new?  call callbacks?
5521        networkAgent.networkCapabilities = networkCapabilities;
5522    }
5523
5524    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
5525        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5526        for (AsyncChannel ac : mNetworkFactories) {
5527            ac.sendMessage(NetworkFactoryProtocol.CMD_REQUEST_NETWORK, score, 0, networkRequest);
5528        }
5529    }
5530
5531    private void callCallbackForRequest(NetworkRequestInfo nri,
5532            NetworkAgentInfo networkAgent, int notificationType) {
5533        if (nri.messenger == null) return;  // Default request has no msgr
5534        Object o;
5535        int a1 = 0;
5536        int a2 = 0;
5537        switch (notificationType) {
5538            case ConnectivityManager.CALLBACK_LOSING:
5539                a1 = 30; // TODO - read this from NetworkMonitor
5540                // fall through
5541            case ConnectivityManager.CALLBACK_PRECHECK:
5542            case ConnectivityManager.CALLBACK_AVAILABLE:
5543            case ConnectivityManager.CALLBACK_LOST:
5544            case ConnectivityManager.CALLBACK_CAP_CHANGED:
5545            case ConnectivityManager.CALLBACK_IP_CHANGED: {
5546                o = new NetworkRequest(nri.request);
5547                a2 = networkAgent.network.netId;
5548                break;
5549            }
5550            case ConnectivityManager.CALLBACK_UNAVAIL:
5551            case ConnectivityManager.CALLBACK_RELEASED: {
5552                o = new NetworkRequest(nri.request);
5553                break;
5554            }
5555            default: {
5556                loge("Unknown notificationType " + notificationType);
5557                return;
5558            }
5559        }
5560        Message msg = Message.obtain();
5561        msg.arg1 = a1;
5562        msg.arg2 = a2;
5563        msg.obj = o;
5564        msg.what = notificationType;
5565        try {
5566            if (VDBG) log("sending notification " + notificationType + " for " + nri.request);
5567            nri.messenger.send(msg);
5568        } catch (RemoteException e) {
5569            // may occur naturally in the race of binder death.
5570            loge("RemoteException caught trying to send a callback msg for " + nri.request);
5571        }
5572    }
5573
5574    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5575        if (oldNetwork == null) {
5576            loge("Unknown NetworkAgentInfo in handleLingerComplete");
5577            return;
5578        }
5579        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
5580        if (DBG) {
5581            if (oldNetwork.networkRequests.size() != 0) {
5582                loge("Dead network still had " + oldNetwork.networkRequests.size() + " requests");
5583            }
5584        }
5585        oldNetwork.asyncChannel.disconnect();
5586    }
5587
5588    private void handleConnectionValidated(NetworkAgentInfo newNetwork) {
5589        if (newNetwork == null) {
5590            loge("Unknown NetworkAgentInfo in handleConnectionValidated");
5591            return;
5592        }
5593        boolean keep = false;
5594        boolean isNewDefault = false;
5595        if (DBG) log("handleConnectionValidated for "+newNetwork.name());
5596        // check if any NetworkRequest wants this NetworkAgent
5597        // first check if it satisfies the NetworkCapabilities
5598        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
5599        if (VDBG) log(" new Network has: " + newNetwork.networkCapabilities);
5600        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5601            if (VDBG) log("  checking if request is satisfied: " + nri.request);
5602            if (nri.request.networkCapabilities.satisfiedByNetworkCapabilities(
5603                    newNetwork.networkCapabilities)) {
5604                // next check if it's better than any current network we're using for
5605                // this request
5606                NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
5607                if (VDBG) {
5608                    log("currentScore = " +
5609                            (currentNetwork != null ? currentNetwork.currentScore : 0) +
5610                            ", newScore = " + newNetwork.currentScore);
5611                }
5612                if (currentNetwork == null ||
5613                        currentNetwork.currentScore < newNetwork.currentScore) {
5614                    if (currentNetwork != null) {
5615                        if (VDBG) log("   accepting network in place of " + currentNetwork.name());
5616                        currentNetwork.networkRequests.remove(nri.request.requestId);
5617                        currentNetwork.networkLingered.add(nri.request);
5618                        affectedNetworks.add(currentNetwork);
5619                    } else {
5620                        if (VDBG) log("   accepting network in place of null");
5621                    }
5622                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
5623                    newNetwork.networkRequests.put(nri.request.requestId, nri.request);
5624                    keep = true;
5625                    // TODO - this could get expensive if we have alot of requests for this
5626                    // network.  Think about if there is a way to reduce this.  Push
5627                    // netid->request mapping to each factory?
5628                    sendUpdatedScoreToFactories(nri.request, newNetwork.currentScore);
5629                    if (mDefaultRequest.requestId == nri.request.requestId) {
5630                        isNewDefault = true;
5631                        updateActiveDefaultNetwork(newNetwork);
5632                        if (newNetwork.linkProperties != null) {
5633                            setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnses());
5634                        } else {
5635                            setDefaultDnsSystemProperties(new ArrayList<InetAddress>());
5636                        }
5637                    }
5638                }
5639            }
5640        }
5641        for (NetworkAgentInfo nai : affectedNetworks) {
5642            boolean teardown = true;
5643            for (int i = 0; i < nai.networkRequests.size(); i++) {
5644                NetworkRequest nr = nai.networkRequests.valueAt(i);
5645                try {
5646                if (mNetworkRequests.get(nr).isRequest) {
5647                    teardown = false;
5648                }
5649                } catch (Exception e) {
5650                    loge("Request " + nr + " not found in mNetworkRequests.");
5651                    loge("  it came from request list  of " + nai.name());
5652                }
5653            }
5654            if (teardown) {
5655                nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
5656                notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
5657            } else {
5658                // not going to linger, so kill the list of linger networks..  only
5659                // notify them of linger if it happens as the result of gaining another,
5660                // but if they transition and old network stays up, don't tell them of linger
5661                // or very delayed loss
5662                nai.networkLingered.clear();
5663                if (VDBG) log("Lingered for " + nai.name() + " cleared");
5664            }
5665        }
5666        if (keep) {
5667            if (isNewDefault) {
5668                if (VDBG) log("Switching to new default network: " + newNetwork);
5669                setupDataActivityTracking(newNetwork);
5670                try {
5671                    mNetd.setDefaultNetId(newNetwork.network.netId);
5672                } catch (Exception e) {
5673                    loge("Exception setting default network :" + e);
5674                }
5675                if (newNetwork.equals(mNetworkForRequestId.get(mDefaultRequest.requestId))) {
5676                    handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
5677                }
5678                synchronized (ConnectivityService.this) {
5679                    // have a new default network, release the transition wakelock in
5680                    // a second if it's held.  The second pause is to allow apps
5681                    // to reconnect over the new network
5682                    if (mNetTransitionWakeLock.isHeld()) {
5683                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
5684                                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
5685                                mNetTransitionWakeLockSerialNumber, 0),
5686                                1000);
5687                    }
5688                }
5689
5690                // this will cause us to come up initially as unconnected and switching
5691                // to connected after our normal pause unless somebody reports us as
5692                // really disconnected
5693                mDefaultInetConditionPublished = 0;
5694                mDefaultConnectionSequence++;
5695                mInetConditionChangeInFlight = false;
5696                // TODO - read the tcp buffer size config string from somewhere
5697                // updateNetworkSettings();
5698            }
5699            // notify battery stats service about this network
5700//            try {
5701                // TODO
5702                //BatteryStatsService.getService().noteNetworkInterfaceType(iface, netType);
5703//            } catch (RemoteException e) { }
5704            notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
5705        } else {
5706            if (DBG && newNetwork.networkRequests.size() != 0) {
5707                loge("tearing down network with live requests:");
5708                for (int i=0; i < newNetwork.networkRequests.size(); i++) {
5709                    loge("  " + newNetwork.networkRequests.valueAt(i));
5710                }
5711            }
5712            if (VDBG) log("Validated network turns out to be unwanted.  Tear it down.");
5713            newNetwork.asyncChannel.disconnect();
5714        }
5715    }
5716
5717
5718    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
5719        NetworkInfo.State state = newInfo.getState();
5720        NetworkInfo oldInfo = networkAgent.networkInfo;
5721        networkAgent.networkInfo = newInfo;
5722
5723        if (oldInfo != null && oldInfo.getState() == state) {
5724            if (VDBG) log("ignoring duplicate network state non-change");
5725            return;
5726        }
5727        if (DBG) {
5728            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5729                    (oldInfo == null ? "null" : oldInfo.getState()) +
5730                    " to " + state);
5731        }
5732
5733        if (state == NetworkInfo.State.CONNECTED) {
5734            // TODO - check if we want it (optimization)
5735            try {
5736                mNetd.createNetwork(networkAgent.network.netId);
5737            } catch (Exception e) {
5738                loge("Error creating Network " + networkAgent.network.netId);
5739            }
5740            updateLinkProperties(networkAgent, null);
5741            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
5742            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
5743        } else if (state == NetworkInfo.State.DISCONNECTED ||
5744                state == NetworkInfo.State.SUSPENDED) {
5745            networkAgent.asyncChannel.disconnect();
5746        }
5747    }
5748
5749    // notify only this one new request of the current state
5750    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5751        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
5752        // TODO - read state from monitor to decide what to send.
5753//        if (nai.networkMonitor.isLingering()) {
5754//            notifyType = NetworkCallbacks.LOSING;
5755//        } else if (nai.networkMonitor.isEvaluating()) {
5756//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
5757//        }
5758        if (nri.request.needsBroadcasts) {
5759        // TODO
5760//            sendNetworkBroadcast(nai, notifyType);
5761        }
5762        callCallbackForRequest(nri, nai, notifyType);
5763    }
5764
5765    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5766        if (VDBG) log("notifyType " + notifyType + " for " + networkAgent.name());
5767        boolean needsBroadcasts = false;
5768        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
5769            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
5770            NetworkRequestInfo nri = mNetworkRequests.get(nr);
5771            if (VDBG) log(" sending notification for " + nr);
5772            if (nr.needsBroadcasts) needsBroadcasts = true;
5773            callCallbackForRequest(nri, networkAgent, notifyType);
5774        }
5775        if (needsBroadcasts) {
5776            if (notifyType == ConnectivityManager.CALLBACK_AVAILABLE) {
5777                sendConnectedBroadcastDelayed(networkAgent.networkInfo,
5778                        getConnectivityChangeDelay());
5779            } else if (notifyType == ConnectivityManager.CALLBACK_LOST) {
5780                NetworkInfo info = new NetworkInfo(networkAgent.networkInfo);
5781                Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5782                intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5783                intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5784                if (info.isFailover()) {
5785                    intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5786                    networkAgent.networkInfo.setFailover(false);
5787                }
5788                if (info.getReason() != null) {
5789                    intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5790                }
5791                if (info.getExtraInfo() != null) {
5792                    intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5793                }
5794                NetworkAgentInfo newDefaultAgent = null;
5795                if (networkAgent.networkRequests.get(mDefaultRequest.requestId) != null) {
5796                    newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
5797                    if (newDefaultAgent != null) {
5798                        intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5799                                newDefaultAgent.networkInfo);
5800                    } else {
5801                        intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5802                    }
5803                }
5804                intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5805                        mDefaultInetConditionPublished);
5806                final Intent immediateIntent = new Intent(intent);
5807                immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
5808                sendStickyBroadcast(immediateIntent);
5809                sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
5810                if (newDefaultAgent != null) {
5811                    sendConnectedBroadcastDelayed(newDefaultAgent.networkInfo,
5812                            getConnectivityChangeDelay());
5813                }
5814            }
5815        }
5816    }
5817
5818    private LinkProperties getLinkPropertiesForTypeInternal(int networkType) {
5819        ArrayList<NetworkAgentInfo> list = mNetworkAgentInfoForType[networkType];
5820        if (list == null) return null;
5821        try {
5822            return new LinkProperties(list.get(0).linkProperties);
5823        } catch (IndexOutOfBoundsException e) {
5824            return new LinkProperties();
5825        }
5826    }
5827
5828    private NetworkInfo getNetworkInfoForType(int networkType) {
5829        ArrayList<NetworkAgentInfo> list = mNetworkAgentInfoForType[networkType];
5830        if (list == null) return null;
5831        try {
5832            return new NetworkInfo(list.get(0).networkInfo);
5833        } catch (IndexOutOfBoundsException e) {
5834            return new NetworkInfo(networkType, 0, "Unknown", "");
5835        }
5836    }
5837
5838    private NetworkCapabilities getNetworkCapabilitiesForType(int networkType) {
5839        ArrayList<NetworkAgentInfo> list = mNetworkAgentInfoForType[networkType];
5840        if (list == null) return null;
5841        try {
5842            return new NetworkCapabilities(list.get(0).networkCapabilities);
5843        } catch (IndexOutOfBoundsException e) {
5844            return new NetworkCapabilities();
5845        }
5846    }
5847}
5848