ConnectivityService.java revision 43074032d6ee3576416c86342da3a7a3291049a7
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.TYPE_BLUETOOTH;
24import static android.net.ConnectivityManager.TYPE_DUMMY;
25import static android.net.ConnectivityManager.TYPE_MOBILE;
26import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
27import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
28import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
29import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
30import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
31import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
32import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
33import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
34import static android.net.ConnectivityManager.TYPE_NONE;
35import static android.net.ConnectivityManager.TYPE_WIFI;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
37import static android.net.ConnectivityManager.TYPE_PROXY;
38import static android.net.ConnectivityManager.getNetworkTypeName;
39import static android.net.ConnectivityManager.isNetworkTypeValid;
40import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
41import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
42
43import android.app.AlarmManager;
44import android.app.Notification;
45import android.app.NotificationManager;
46import android.app.PendingIntent;
47import android.content.ActivityNotFoundException;
48import android.content.BroadcastReceiver;
49import android.content.ContentResolver;
50import android.content.Context;
51import android.content.ContextWrapper;
52import android.content.Intent;
53import android.content.IntentFilter;
54import android.content.pm.PackageManager;
55import android.content.res.Configuration;
56import android.content.res.Resources;
57import android.database.ContentObserver;
58import android.net.ConnectivityManager;
59import android.net.IConnectivityManager;
60import android.net.INetworkManagementEventObserver;
61import android.net.INetworkPolicyListener;
62import android.net.INetworkPolicyManager;
63import android.net.INetworkStatsService;
64import android.net.LinkAddress;
65import android.net.LinkProperties;
66import android.net.LinkProperties.CompareResult;
67import android.net.LinkQualityInfo;
68import android.net.MobileDataStateTracker;
69import android.net.Network;
70import android.net.NetworkAgent;
71import android.net.NetworkCapabilities;
72import android.net.NetworkConfig;
73import android.net.NetworkInfo;
74import android.net.NetworkInfo.DetailedState;
75import android.net.NetworkFactory;
76import android.net.NetworkMisc;
77import android.net.NetworkQuotaInfo;
78import android.net.NetworkRequest;
79import android.net.NetworkState;
80import android.net.NetworkStateTracker;
81import android.net.NetworkUtils;
82import android.net.Proxy;
83import android.net.ProxyDataTracker;
84import android.net.ProxyInfo;
85import android.net.RouteInfo;
86import android.net.SamplingDataTracker;
87import android.net.UidRange;
88import android.net.Uri;
89import android.net.wimax.WimaxManagerConstants;
90import android.os.AsyncTask;
91import android.os.Binder;
92import android.os.Build;
93import android.os.FileUtils;
94import android.os.Handler;
95import android.os.HandlerThread;
96import android.os.IBinder;
97import android.os.INetworkManagementService;
98import android.os.Looper;
99import android.os.Message;
100import android.os.Messenger;
101import android.os.ParcelFileDescriptor;
102import android.os.PowerManager;
103import android.os.Process;
104import android.os.RemoteException;
105import android.os.ServiceManager;
106import android.os.SystemClock;
107import android.os.SystemProperties;
108import android.os.UserHandle;
109import android.os.UserManager;
110import android.provider.Settings;
111import android.security.Credentials;
112import android.security.KeyStore;
113import android.telephony.TelephonyManager;
114import android.text.TextUtils;
115import android.util.Slog;
116import android.util.SparseArray;
117import android.util.SparseIntArray;
118import android.util.Xml;
119
120import com.android.internal.R;
121import com.android.internal.annotations.GuardedBy;
122import com.android.internal.app.IBatteryStats;
123import com.android.internal.net.LegacyVpnInfo;
124import com.android.internal.net.NetworkStatsFactory;
125import com.android.internal.net.VpnConfig;
126import com.android.internal.net.VpnProfile;
127import com.android.internal.telephony.DctConstants;
128import com.android.internal.telephony.Phone;
129import com.android.internal.telephony.PhoneConstants;
130import com.android.internal.telephony.TelephonyIntents;
131import com.android.internal.util.AsyncChannel;
132import com.android.internal.util.IndentingPrintWriter;
133import com.android.internal.util.XmlUtils;
134import com.android.server.am.BatteryStatsService;
135import com.android.server.connectivity.DataConnectionStats;
136import com.android.server.connectivity.Nat464Xlat;
137import com.android.server.connectivity.NetworkAgentInfo;
138import com.android.server.connectivity.NetworkMonitor;
139import com.android.server.connectivity.PacManager;
140import com.android.server.connectivity.Tethering;
141import com.android.server.connectivity.Vpn;
142import com.android.server.net.BaseNetworkObserver;
143import com.android.server.net.LockdownVpnTracker;
144import com.google.android.collect.Lists;
145import com.google.android.collect.Sets;
146
147import dalvik.system.DexClassLoader;
148
149import org.xmlpull.v1.XmlPullParser;
150import org.xmlpull.v1.XmlPullParserException;
151
152import java.io.File;
153import java.io.FileDescriptor;
154import java.io.FileNotFoundException;
155import java.io.FileReader;
156import java.io.IOException;
157import java.io.PrintWriter;
158import java.lang.reflect.Constructor;
159import java.net.HttpURLConnection;
160import java.net.Inet4Address;
161import java.net.Inet6Address;
162import java.net.InetAddress;
163import java.net.URL;
164import java.net.UnknownHostException;
165import java.util.ArrayList;
166import java.util.Arrays;
167import java.util.Collection;
168import java.util.GregorianCalendar;
169import java.util.HashMap;
170import java.util.HashSet;
171import java.util.List;
172import java.util.Map;
173import java.util.Random;
174import java.util.concurrent.atomic.AtomicBoolean;
175import java.util.concurrent.atomic.AtomicInteger;
176
177import javax.net.ssl.HostnameVerifier;
178import javax.net.ssl.HttpsURLConnection;
179import javax.net.ssl.SSLSession;
180
181/**
182 * @hide
183 */
184public class ConnectivityService extends IConnectivityManager.Stub {
185    private static final String TAG = "ConnectivityService";
186
187    private static final boolean DBG = true;
188    private static final boolean VDBG = true; // STOPSHIP
189
190    // network sampling debugging
191    private static final boolean SAMPLE_DBG = false;
192
193    private static final boolean LOGD_RULES = false;
194
195    // TODO: create better separation between radio types and network types
196
197    // how long to wait before switching back to a radio's default network
198    private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
199    // system property that can override the above value
200    private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
201            "android.telephony.apn-restore";
202
203    // Default value if FAIL_FAST_TIME_MS is not set
204    private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
205    // system property that can override DEFAULT_FAIL_FAST_TIME_MS
206    private static final String FAIL_FAST_TIME_MS =
207            "persist.radio.fail_fast_time_ms";
208
209    private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
210            "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
211
212    private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
213
214    private PendingIntent mSampleIntervalElapsedIntent;
215
216    // Set network sampling interval at 12 minutes, this way, even if the timers get
217    // aggregated, it will fire at around 15 minutes, which should allow us to
218    // aggregate this timer with other timers (specially the socket keep alive timers)
219    private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 12 * 60);
220
221    // start network sampling a minute after booting ...
222    private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 60);
223
224    AlarmManager mAlarmManager;
225
226    private Tethering mTethering;
227
228    private KeyStore mKeyStore;
229
230    @GuardedBy("mVpns")
231    private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
232
233    private boolean mLockdownEnabled;
234    private LockdownVpnTracker mLockdownTracker;
235
236    private Nat464Xlat mClat;
237
238    /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
239    private Object mRulesLock = new Object();
240    /** Currently active network rules by UID. */
241    private SparseIntArray mUidRules = new SparseIntArray();
242    /** Set of ifaces that are costly. */
243    private HashSet<String> mMeteredIfaces = Sets.newHashSet();
244
245    /**
246     * Sometimes we want to refer to the individual network state
247     * trackers separately, and sometimes we just want to treat them
248     * abstractly.
249     */
250    private NetworkStateTracker mNetTrackers[];
251
252    private Context mContext;
253    private int mNetworkPreference;
254    private int mActiveDefaultNetwork = -1;
255    // 0 is full bad, 100 is full good
256    private int mDefaultInetConditionPublished = 0;
257
258    private Object mDnsLock = new Object();
259    private int mNumDnsEntries;
260
261    private boolean mTestMode;
262    private static ConnectivityService sServiceInstance;
263
264    private INetworkManagementService mNetd;
265    private INetworkPolicyManager mPolicyManager;
266
267    private static final int ENABLED  = 1;
268    private static final int DISABLED = 0;
269
270    /**
271     * used internally to change our mobile data enabled flag
272     */
273    private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
274
275    /**
276     * used internally to clear a wakelock when transitioning
277     * from one net to another.  Clear happens when we get a new
278     * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
279     * after a timeout if no network is found (typically 1 min).
280     */
281    private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
282
283    /**
284     * used internally to reload global proxy settings
285     */
286    private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
287
288    /**
289     * used internally to set external dependency met/unmet
290     * arg1 = ENABLED (met) or DISABLED (unmet)
291     * arg2 = NetworkType
292     */
293    private static final int EVENT_SET_DEPENDENCY_MET = 10;
294
295    /**
296     * used internally to send a sticky broadcast delayed.
297     */
298    private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
299
300    /**
301     * Used internally to
302     * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
303     */
304    private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
305
306    /**
307     * Used internally to disable fail fast of mobile data
308     */
309    private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
310
311    /**
312     * used internally to indicate that data sampling interval is up
313     */
314    private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
315
316    /**
317     * PAC manager has received new port.
318     */
319    private static final int EVENT_PROXY_HAS_CHANGED = 16;
320
321    /**
322     * used internally when registering NetworkFactories
323     * obj = NetworkFactoryInfo
324     */
325    private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
326
327    /**
328     * used internally when registering NetworkAgents
329     * obj = Messenger
330     */
331    private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
332
333    /**
334     * used to add a network request
335     * includes a NetworkRequestInfo
336     */
337    private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
338
339    /**
340     * indicates a timeout period is over - check if we had a network yet or not
341     * and if not, call the timeout calback (but leave the request live until they
342     * cancel it.
343     * includes a NetworkRequestInfo
344     */
345    private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
346
347    /**
348     * used to add a network listener - no request
349     * includes a NetworkRequestInfo
350     */
351    private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
352
353    /**
354     * used to remove a network request, either a listener or a real request
355     * arg1 = UID of caller
356     * obj  = NetworkRequest
357     */
358    private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
359
360    /**
361     * used internally when registering NetworkFactories
362     * obj = Messenger
363     */
364    private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
365
366    /**
367     * used internally to expire a wakelock when transitioning
368     * from one net to another.  Expire happens when we fail to find
369     * a new network (typically after 1 minute) -
370     * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
371     * a replacement network.
372     */
373    private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
374
375    /**
376     * Used internally to indicate the system is ready.
377     */
378    private static final int EVENT_SYSTEM_READY = 25;
379
380
381    /** Handler used for internal events. */
382    final private InternalHandler mHandler;
383    /** Handler used for incoming {@link NetworkStateTracker} events. */
384    final private NetworkStateTrackerHandler mTrackerHandler;
385
386    private boolean mSystemReady;
387    private Intent mInitialBroadcast;
388
389    private PowerManager.WakeLock mNetTransitionWakeLock;
390    private String mNetTransitionWakeLockCausedBy = "";
391    private int mNetTransitionWakeLockSerialNumber;
392    private int mNetTransitionWakeLockTimeout;
393
394    private InetAddress mDefaultDns;
395
396    // used in DBG mode to track inet condition reports
397    private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
398    private ArrayList mInetLog;
399
400    // track the current default http proxy - tell the world if we get a new one (real change)
401    private ProxyInfo mDefaultProxy = null;
402    private Object mProxyLock = new Object();
403    private boolean mDefaultProxyDisabled = false;
404
405    // track the global proxy.
406    private ProxyInfo mGlobalProxy = null;
407
408    private PacManager mPacManager = null;
409
410    private SettingsObserver mSettingsObserver;
411
412    private UserManager mUserManager;
413
414    NetworkConfig[] mNetConfigs;
415    int mNetworksDefined;
416
417    // the set of network types that can only be enabled by system/sig apps
418    List mProtectedNetworks;
419
420    private DataConnectionStats mDataConnectionStats;
421
422    private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
423
424    TelephonyManager mTelephonyManager;
425
426    // sequence number for Networks
427    private final static int MIN_NET_ID = 10; // some reserved marks
428    private final static int MAX_NET_ID = 65535;
429    private int mNextNetId = MIN_NET_ID;
430
431    // sequence number of NetworkRequests
432    private int mNextNetworkRequestId = 1;
433
434    /**
435     * Implements support for the legacy "one network per network type" model.
436     *
437     * We used to have a static array of NetworkStateTrackers, one for each
438     * network type, but that doesn't work any more now that we can have,
439     * for example, more that one wifi network. This class stores all the
440     * NetworkAgentInfo objects that support a given type, but the legacy
441     * API will only see the first one.
442     *
443     * It serves two main purposes:
444     *
445     * 1. Provide information about "the network for a given type" (since this
446     *    API only supports one).
447     * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
448     *    the first network for a given type changes, or if the default network
449     *    changes.
450     */
451    private class LegacyTypeTracker {
452
453        private static final boolean DBG = true;
454        private static final boolean VDBG = false;
455        private static final String TAG = "CSLegacyTypeTracker";
456
457        /**
458         * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
459         * Each list holds references to all NetworkAgentInfos that are used to
460         * satisfy requests for that network type.
461         *
462         * This array is built out at startup such that an unsupported network
463         * doesn't get an ArrayList instance, making this a tristate:
464         * unsupported, supported but not active and active.
465         *
466         * The actual lists are populated when we scan the network types that
467         * are supported on this device.
468         */
469        private ArrayList<NetworkAgentInfo> mTypeLists[];
470
471        public LegacyTypeTracker() {
472            mTypeLists = (ArrayList<NetworkAgentInfo>[])
473                    new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
474        }
475
476        public void addSupportedType(int type) {
477            if (mTypeLists[type] != null) {
478                throw new IllegalStateException(
479                        "legacy list for type " + type + "already initialized");
480            }
481            mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
482        }
483
484        public boolean isTypeSupported(int type) {
485            return isNetworkTypeValid(type) && mTypeLists[type] != null;
486        }
487
488        public NetworkAgentInfo getNetworkForType(int type) {
489            if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
490                return mTypeLists[type].get(0);
491            } else {
492                return null;
493            }
494        }
495
496        private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
497            if (DBG) {
498                log("Sending " + (connected ? "connected" : "disconnected") +
499                        " broadcast for type " + type + " " + nai.name() +
500                        " isDefaultNetwork=" + isDefaultNetwork(nai));
501            }
502        }
503
504        /** Adds the given network to the specified legacy type list. */
505        public void add(int type, NetworkAgentInfo nai) {
506            if (!isTypeSupported(type)) {
507                return;  // Invalid network type.
508            }
509            if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
510
511            ArrayList<NetworkAgentInfo> list = mTypeLists[type];
512            if (list.contains(nai)) {
513                loge("Attempting to register duplicate agent for type " + type + ": " + nai);
514                return;
515            }
516
517            if (list.isEmpty() || isDefaultNetwork(nai)) {
518                maybeLogBroadcast(nai, true, type);
519                sendLegacyNetworkBroadcast(nai, true, type);
520            }
521            list.add(nai);
522        }
523
524        /** Removes the given network from the specified legacy type list. */
525        public void remove(int type, NetworkAgentInfo nai) {
526            ArrayList<NetworkAgentInfo> list = mTypeLists[type];
527            if (list == null || list.isEmpty()) {
528                return;
529            }
530
531            boolean wasFirstNetwork = list.get(0).equals(nai);
532
533            if (!list.remove(nai)) {
534                return;
535            }
536
537            if (wasFirstNetwork || isDefaultNetwork(nai)) {
538                maybeLogBroadcast(nai, false, type);
539                sendLegacyNetworkBroadcast(nai, false, type);
540            }
541
542            if (!list.isEmpty() && wasFirstNetwork) {
543                if (DBG) log("Other network available for type " + type +
544                              ", sending connected broadcast");
545                maybeLogBroadcast(list.get(0), false, type);
546                sendLegacyNetworkBroadcast(list.get(0), false, type);
547            }
548        }
549
550        /** Removes the given network from all legacy type lists. */
551        public void remove(NetworkAgentInfo nai) {
552            if (VDBG) log("Removing agent " + nai);
553            for (int type = 0; type < mTypeLists.length; type++) {
554                remove(type, nai);
555            }
556        }
557
558        private String naiToString(NetworkAgentInfo nai) {
559            String name = (nai != null) ? nai.name() : "null";
560            String state = (nai.networkInfo != null) ?
561                    nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
562                    "???/???";
563            return name + " " + state;
564        }
565
566        public void dump(IndentingPrintWriter pw) {
567            for (int type = 0; type < mTypeLists.length; type++) {
568                if (mTypeLists[type] == null) continue;
569                pw.print(type + " ");
570                pw.increaseIndent();
571                if (mTypeLists[type].size() == 0) pw.println("none");
572                for (NetworkAgentInfo nai : mTypeLists[type]) {
573                    pw.println(naiToString(nai));
574                }
575                pw.decreaseIndent();
576            }
577        }
578
579        // This class needs its own log method because it has a different TAG.
580        private void log(String s) {
581            Slog.d(TAG, s);
582        }
583
584    }
585    private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
586
587    public ConnectivityService(Context context, INetworkManagementService netManager,
588            INetworkStatsService statsService, INetworkPolicyManager policyManager) {
589        if (DBG) log("ConnectivityService starting up");
590
591        NetworkCapabilities netCap = new NetworkCapabilities();
592        netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
593        netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
594        mDefaultRequest = new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
595        NetworkRequestInfo nri = new NetworkRequestInfo(null, mDefaultRequest, new Binder(),
596                NetworkRequestInfo.REQUEST);
597        mNetworkRequests.put(mDefaultRequest, nri);
598
599        HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
600        handlerThread.start();
601        mHandler = new InternalHandler(handlerThread.getLooper());
602        mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
603
604        // setup our unique device name
605        if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
606            String id = Settings.Secure.getString(context.getContentResolver(),
607                    Settings.Secure.ANDROID_ID);
608            if (id != null && id.length() > 0) {
609                String name = new String("android-").concat(id);
610                SystemProperties.set("net.hostname", name);
611            }
612        }
613
614        // read our default dns server ip
615        String dns = Settings.Global.getString(context.getContentResolver(),
616                Settings.Global.DEFAULT_DNS_SERVER);
617        if (dns == null || dns.length() == 0) {
618            dns = context.getResources().getString(
619                    com.android.internal.R.string.config_default_dns_server);
620        }
621        try {
622            mDefaultDns = NetworkUtils.numericToInetAddress(dns);
623        } catch (IllegalArgumentException e) {
624            loge("Error setting defaultDns using " + dns);
625        }
626
627        mContext = checkNotNull(context, "missing Context");
628        mNetd = checkNotNull(netManager, "missing INetworkManagementService");
629        mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
630        mKeyStore = KeyStore.getInstance();
631        mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
632
633        try {
634            mPolicyManager.registerListener(mPolicyListener);
635        } catch (RemoteException e) {
636            // ouch, no rules updates means some processes may never get network
637            loge("unable to register INetworkPolicyListener" + e.toString());
638        }
639
640        final PowerManager powerManager = (PowerManager) context.getSystemService(
641                Context.POWER_SERVICE);
642        mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
643        mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
644                com.android.internal.R.integer.config_networkTransitionTimeout);
645
646        mNetTrackers = new NetworkStateTracker[
647                ConnectivityManager.MAX_NETWORK_TYPE+1];
648
649        mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
650
651        // TODO: What is the "correct" way to do determine if this is a wifi only device?
652        boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
653        log("wifiOnly=" + wifiOnly);
654        String[] naStrings = context.getResources().getStringArray(
655                com.android.internal.R.array.networkAttributes);
656        for (String naString : naStrings) {
657            try {
658                NetworkConfig n = new NetworkConfig(naString);
659                if (VDBG) log("naString=" + naString + " config=" + n);
660                if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
661                    loge("Error in networkAttributes - ignoring attempt to define type " +
662                            n.type);
663                    continue;
664                }
665                if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
666                    log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
667                            n.type);
668                    continue;
669                }
670                if (mNetConfigs[n.type] != null) {
671                    loge("Error in networkAttributes - ignoring attempt to redefine type " +
672                            n.type);
673                    continue;
674                }
675                mLegacyTypeTracker.addSupportedType(n.type);
676
677                mNetConfigs[n.type] = n;
678                mNetworksDefined++;
679            } catch(Exception e) {
680                // ignore it - leave the entry null
681            }
682        }
683        if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
684
685        mProtectedNetworks = new ArrayList<Integer>();
686        int[] protectedNetworks = context.getResources().getIntArray(
687                com.android.internal.R.array.config_protectedNetworks);
688        for (int p : protectedNetworks) {
689            if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
690                mProtectedNetworks.add(p);
691            } else {
692                if (DBG) loge("Ignoring protectedNetwork " + p);
693            }
694        }
695
696        mTestMode = SystemProperties.get("cm.test.mode").equals("true")
697                && SystemProperties.get("ro.build.type").equals("eng");
698
699        mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
700
701        //set up the listener for user state for creating user VPNs
702        IntentFilter intentFilter = new IntentFilter();
703        intentFilter.addAction(Intent.ACTION_USER_STARTING);
704        intentFilter.addAction(Intent.ACTION_USER_STOPPING);
705        mContext.registerReceiverAsUser(
706                mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
707        mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
708
709        try {
710            mNetd.registerObserver(mTethering);
711            mNetd.registerObserver(mDataActivityObserver);
712            mNetd.registerObserver(mClat);
713        } catch (RemoteException e) {
714            loge("Error registering observer :" + e);
715        }
716
717        if (DBG) {
718            mInetLog = new ArrayList();
719        }
720
721        mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
722        mSettingsObserver.observe(mContext);
723
724        mDataConnectionStats = new DataConnectionStats(mContext);
725        mDataConnectionStats.startMonitoring();
726
727        mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
728
729        IntentFilter filter = new IntentFilter();
730        filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
731        mContext.registerReceiver(
732                new BroadcastReceiver() {
733                    @Override
734                    public void onReceive(Context context, Intent intent) {
735                        String action = intent.getAction();
736                        if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
737                            mHandler.sendMessage(mHandler.obtainMessage
738                                    (EVENT_SAMPLE_INTERVAL_ELAPSED));
739                        }
740                    }
741                },
742                new IntentFilter(filter));
743
744        mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
745
746        filter = new IntentFilter();
747        filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
748        mContext.registerReceiver(mProvisioningReceiver, filter);
749
750        mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
751    }
752
753    private synchronized int nextNetworkRequestId() {
754        return mNextNetworkRequestId++;
755    }
756
757    private synchronized int nextNetId() {
758        int netId = mNextNetId;
759        if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
760        return netId;
761    }
762
763    private int getConnectivityChangeDelay() {
764        final ContentResolver cr = mContext.getContentResolver();
765
766        /** Check system properties for the default value then use secure settings value, if any. */
767        int defaultDelay = SystemProperties.getInt(
768                "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
769                ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
770        return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
771                defaultDelay);
772    }
773
774    private boolean teardown(NetworkStateTracker netTracker) {
775        if (netTracker.teardown()) {
776            netTracker.setTeardownRequested(true);
777            return true;
778        } else {
779            return false;
780        }
781    }
782
783    /**
784     * Check if UID should be blocked from using the network represented by the
785     * given {@link NetworkStateTracker}.
786     */
787    private boolean isNetworkBlocked(int networkType, int uid) {
788        final boolean networkCostly;
789        final int uidRules;
790
791        LinkProperties lp = getLinkPropertiesForType(networkType);
792        final String iface = (lp == null ? "" : lp.getInterfaceName());
793        synchronized (mRulesLock) {
794            networkCostly = mMeteredIfaces.contains(iface);
795            uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
796        }
797
798        if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
799            return true;
800        }
801
802        // no restrictive rules; network is visible
803        return false;
804    }
805
806    /**
807     * Return a filtered {@link NetworkInfo}, potentially marked
808     * {@link DetailedState#BLOCKED} based on
809     * {@link #isNetworkBlocked}.
810     */
811    private NetworkInfo getFilteredNetworkInfo(int networkType, int uid) {
812        NetworkInfo info = getNetworkInfoForType(networkType);
813        return getFilteredNetworkInfo(info, networkType, uid);
814    }
815
816    private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, int networkType, int uid) {
817        if (isNetworkBlocked(networkType, uid)) {
818            // network is blocked; clone and override state
819            info = new NetworkInfo(info);
820            info.setDetailedState(DetailedState.BLOCKED, null, null);
821            if (VDBG) log("returning Blocked NetworkInfo");
822        }
823        if (mLockdownTracker != null) {
824            info = mLockdownTracker.augmentNetworkInfo(info);
825            if (VDBG) log("returning Locked NetworkInfo");
826        }
827        return info;
828    }
829
830    /**
831     * Return NetworkInfo for the active (i.e., connected) network interface.
832     * It is assumed that at most one network is active at a time. If more
833     * than one is active, it is indeterminate which will be returned.
834     * @return the info for the active network, or {@code null} if none is
835     * active
836     */
837    @Override
838    public NetworkInfo getActiveNetworkInfo() {
839        enforceAccessPermission();
840        final int uid = Binder.getCallingUid();
841        return getNetworkInfo(mActiveDefaultNetwork, uid);
842    }
843
844    // only called when the default request is satisfied
845    private void updateActiveDefaultNetwork(NetworkAgentInfo nai) {
846        if (nai != null) {
847            mActiveDefaultNetwork = nai.networkInfo.getType();
848        } else {
849            mActiveDefaultNetwork = TYPE_NONE;
850        }
851    }
852
853    /**
854     * Find the first Provisioning network.
855     *
856     * @return NetworkInfo or null if none.
857     */
858    private NetworkInfo getProvisioningNetworkInfo() {
859        enforceAccessPermission();
860
861        // Find the first Provisioning Network
862        NetworkInfo provNi = null;
863        for (NetworkInfo ni : getAllNetworkInfo()) {
864            if (ni.isConnectedToProvisioningNetwork()) {
865                provNi = ni;
866                break;
867            }
868        }
869        if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
870        return provNi;
871    }
872
873    /**
874     * Find the first Provisioning network or the ActiveDefaultNetwork
875     * if there is no Provisioning network
876     *
877     * @return NetworkInfo or null if none.
878     */
879    @Override
880    public NetworkInfo getProvisioningOrActiveNetworkInfo() {
881        enforceAccessPermission();
882
883        NetworkInfo provNi = getProvisioningNetworkInfo();
884        if (provNi == null) {
885            final int uid = Binder.getCallingUid();
886            provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
887        }
888        if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
889        return provNi;
890    }
891
892    public NetworkInfo getActiveNetworkInfoUnfiltered() {
893        enforceAccessPermission();
894        if (isNetworkTypeValid(mActiveDefaultNetwork)) {
895            return getNetworkInfoForType(mActiveDefaultNetwork);
896        }
897        return null;
898    }
899
900    @Override
901    public NetworkInfo getActiveNetworkInfoForUid(int uid) {
902        enforceConnectivityInternalPermission();
903        return getNetworkInfo(mActiveDefaultNetwork, uid);
904    }
905
906    @Override
907    public NetworkInfo getNetworkInfo(int networkType) {
908        enforceAccessPermission();
909        final int uid = Binder.getCallingUid();
910        return getNetworkInfo(networkType, uid);
911    }
912
913    private NetworkInfo getNetworkInfo(int networkType, int uid) {
914        NetworkInfo info = null;
915        if (isNetworkTypeValid(networkType)) {
916            if (getNetworkInfoForType(networkType) != null) {
917                info = getFilteredNetworkInfo(networkType, uid);
918            }
919        }
920        return info;
921    }
922
923    @Override
924    public NetworkInfo getNetworkInfoForNetwork(Network network) {
925        enforceAccessPermission();
926        if (network == null) return null;
927
928        final int uid = Binder.getCallingUid();
929        NetworkAgentInfo nai = null;
930        synchronized (mNetworkForNetId) {
931            nai = mNetworkForNetId.get(network.netId);
932        }
933        if (nai == null) return null;
934        synchronized (nai) {
935            if (nai.networkInfo == null) return null;
936
937            return getFilteredNetworkInfo(nai.networkInfo, nai.networkInfo.getType(), uid);
938        }
939    }
940
941    @Override
942    public NetworkInfo[] getAllNetworkInfo() {
943        enforceAccessPermission();
944        final int uid = Binder.getCallingUid();
945        final ArrayList<NetworkInfo> result = Lists.newArrayList();
946        synchronized (mRulesLock) {
947            for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
948                    networkType++) {
949                if (getNetworkInfoForType(networkType) != null) {
950                    result.add(getFilteredNetworkInfo(networkType, uid));
951                }
952            }
953        }
954        return result.toArray(new NetworkInfo[result.size()]);
955    }
956
957    @Override
958    public Network[] getAllNetworks() {
959        enforceAccessPermission();
960        final ArrayList<Network> result = new ArrayList();
961        synchronized (mNetworkForNetId) {
962            for (int i = 0; i < mNetworkForNetId.size(); i++) {
963                result.add(new Network(mNetworkForNetId.valueAt(i).network));
964            }
965        }
966        return result.toArray(new Network[result.size()]);
967    }
968
969    @Override
970    public boolean isNetworkSupported(int networkType) {
971        enforceAccessPermission();
972        return (isNetworkTypeValid(networkType) && (getNetworkInfoForType(networkType) != null));
973    }
974
975    /**
976     * Return LinkProperties for the active (i.e., connected) default
977     * network interface.  It is assumed that at most one default network
978     * is active at a time. If more than one is active, it is indeterminate
979     * which will be returned.
980     * @return the ip properties for the active network, or {@code null} if
981     * none is active
982     */
983    @Override
984    public LinkProperties getActiveLinkProperties() {
985        return getLinkPropertiesForType(mActiveDefaultNetwork);
986    }
987
988    @Override
989    public LinkProperties getLinkPropertiesForType(int networkType) {
990        enforceAccessPermission();
991        if (isNetworkTypeValid(networkType)) {
992            return getLinkPropertiesForTypeInternal(networkType);
993        }
994        return null;
995    }
996
997    // TODO - this should be ALL networks
998    @Override
999    public LinkProperties getLinkProperties(Network network) {
1000        enforceAccessPermission();
1001        NetworkAgentInfo nai = null;
1002        synchronized (mNetworkForNetId) {
1003            nai = mNetworkForNetId.get(network.netId);
1004        }
1005
1006        if (nai != null) {
1007            synchronized (nai) {
1008                return new LinkProperties(nai.linkProperties);
1009            }
1010        }
1011        return null;
1012    }
1013
1014    @Override
1015    public NetworkCapabilities getNetworkCapabilities(Network network) {
1016        enforceAccessPermission();
1017        NetworkAgentInfo nai = null;
1018        synchronized (mNetworkForNetId) {
1019            nai = mNetworkForNetId.get(network.netId);
1020        }
1021        if (nai != null) {
1022            synchronized (nai) {
1023                return new NetworkCapabilities(nai.networkCapabilities);
1024            }
1025        }
1026        return null;
1027    }
1028
1029    @Override
1030    public NetworkState[] getAllNetworkState() {
1031        enforceAccessPermission();
1032        final int uid = Binder.getCallingUid();
1033        final ArrayList<NetworkState> result = Lists.newArrayList();
1034        synchronized (mRulesLock) {
1035            for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1036                    networkType++) {
1037                if (getNetworkInfoForType(networkType) != null) {
1038                    final NetworkInfo info = getFilteredNetworkInfo(networkType, uid);
1039                    final LinkProperties lp = getLinkPropertiesForTypeInternal(networkType);
1040                    final NetworkCapabilities netcap = getNetworkCapabilitiesForType(networkType);
1041                    result.add(new NetworkState(info, lp, netcap));
1042                }
1043            }
1044        }
1045        return result.toArray(new NetworkState[result.size()]);
1046    }
1047
1048    private NetworkState getNetworkStateUnchecked(int networkType) {
1049        if (isNetworkTypeValid(networkType)) {
1050            NetworkInfo info = getNetworkInfoForType(networkType);
1051            if (info != null) {
1052                return new NetworkState(info,
1053                        getLinkPropertiesForTypeInternal(networkType),
1054                        getNetworkCapabilitiesForType(networkType));
1055            }
1056        }
1057        return null;
1058    }
1059
1060    @Override
1061    public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1062        enforceAccessPermission();
1063
1064        final long token = Binder.clearCallingIdentity();
1065        try {
1066            final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
1067            if (state != null) {
1068                try {
1069                    return mPolicyManager.getNetworkQuotaInfo(state);
1070                } catch (RemoteException e) {
1071                }
1072            }
1073            return null;
1074        } finally {
1075            Binder.restoreCallingIdentity(token);
1076        }
1077    }
1078
1079    @Override
1080    public boolean isActiveNetworkMetered() {
1081        enforceAccessPermission();
1082        final long token = Binder.clearCallingIdentity();
1083        try {
1084            return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
1085        } finally {
1086            Binder.restoreCallingIdentity(token);
1087        }
1088    }
1089
1090    private boolean isNetworkMeteredUnchecked(int networkType) {
1091        final NetworkState state = getNetworkStateUnchecked(networkType);
1092        if (state != null) {
1093            try {
1094                return mPolicyManager.isNetworkMetered(state);
1095            } catch (RemoteException e) {
1096            }
1097        }
1098        return false;
1099    }
1100
1101    private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1102        @Override
1103        public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
1104            int deviceType = Integer.parseInt(label);
1105            sendDataActivityBroadcast(deviceType, active, tsNanos);
1106        }
1107    };
1108
1109    /**
1110     * Ensure that a network route exists to deliver traffic to the specified
1111     * host via the specified network interface.
1112     * @param networkType the type of the network over which traffic to the
1113     * specified host is to be routed
1114     * @param hostAddress the IP address of the host to which the route is
1115     * desired
1116     * @return {@code true} on success, {@code false} on failure
1117     */
1118    public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
1119        enforceChangePermission();
1120        if (mProtectedNetworks.contains(networkType)) {
1121            enforceConnectivityInternalPermission();
1122        }
1123
1124        InetAddress addr;
1125        try {
1126            addr = InetAddress.getByAddress(hostAddress);
1127        } catch (UnknownHostException e) {
1128            if (DBG) log("requestRouteToHostAddress got " + e.toString());
1129            return false;
1130        }
1131
1132        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1133            if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1134            return false;
1135        }
1136
1137        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1138        if (nai == null) {
1139            if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1140                if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1141            } else {
1142                if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1143            }
1144            return false;
1145        }
1146
1147        DetailedState netState;
1148        synchronized (nai) {
1149            netState = nai.networkInfo.getDetailedState();
1150        }
1151
1152        if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
1153            if (VDBG) {
1154                log("requestRouteToHostAddress on down network "
1155                        + "(" + networkType + ") - dropped"
1156                        + " netState=" + netState);
1157            }
1158            return false;
1159        }
1160
1161        final int uid = Binder.getCallingUid();
1162        final long token = Binder.clearCallingIdentity();
1163        try {
1164            LinkProperties lp;
1165            int netId;
1166            synchronized (nai) {
1167                lp = nai.linkProperties;
1168                netId = nai.network.netId;
1169            }
1170            boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
1171            if (DBG) log("requestRouteToHostAddress ok=" + ok);
1172            return ok;
1173        } finally {
1174            Binder.restoreCallingIdentity(token);
1175        }
1176    }
1177
1178    private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
1179        RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1180        if (bestRoute == null) {
1181            bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1182        } else {
1183            String iface = bestRoute.getInterface();
1184            if (bestRoute.getGateway().equals(addr)) {
1185                // if there is no better route, add the implied hostroute for our gateway
1186                bestRoute = RouteInfo.makeHostRoute(addr, iface);
1187            } else {
1188                // if we will connect to this through another route, add a direct route
1189                // to it's gateway
1190                bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1191            }
1192        }
1193        if (VDBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
1194        try {
1195            mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1196        } catch (Exception e) {
1197            // never crash - catch them all
1198            if (DBG) loge("Exception trying to add a route: " + e);
1199            return false;
1200        }
1201        return true;
1202    }
1203
1204    public void setDataDependency(int networkType, boolean met) {
1205        enforceConnectivityInternalPermission();
1206
1207        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1208                (met ? ENABLED : DISABLED), networkType));
1209    }
1210
1211    private void handleSetDependencyMet(int networkType, boolean met) {
1212        if (mNetTrackers[networkType] != null) {
1213            if (DBG) {
1214                log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1215            }
1216            mNetTrackers[networkType].setDependencyMet(met);
1217        }
1218    }
1219
1220    private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1221        @Override
1222        public void onUidRulesChanged(int uid, int uidRules) {
1223            // caller is NPMS, since we only register with them
1224            if (LOGD_RULES) {
1225                log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1226            }
1227
1228            synchronized (mRulesLock) {
1229                // skip update when we've already applied rules
1230                final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1231                if (oldRules == uidRules) return;
1232
1233                mUidRules.put(uid, uidRules);
1234            }
1235
1236            // TODO: notify UID when it has requested targeted updates
1237        }
1238
1239        @Override
1240        public void onMeteredIfacesChanged(String[] meteredIfaces) {
1241            // caller is NPMS, since we only register with them
1242            if (LOGD_RULES) {
1243                log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1244            }
1245
1246            synchronized (mRulesLock) {
1247                mMeteredIfaces.clear();
1248                for (String iface : meteredIfaces) {
1249                    mMeteredIfaces.add(iface);
1250                }
1251            }
1252        }
1253
1254        @Override
1255        public void onRestrictBackgroundChanged(boolean restrictBackground) {
1256            // caller is NPMS, since we only register with them
1257            if (LOGD_RULES) {
1258                log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1259            }
1260
1261            // kick off connectivity change broadcast for active network, since
1262            // global background policy change is radical.
1263            final int networkType = mActiveDefaultNetwork;
1264            if (isNetworkTypeValid(networkType)) {
1265                final NetworkStateTracker tracker = mNetTrackers[networkType];
1266                if (tracker != null) {
1267                    final NetworkInfo info = tracker.getNetworkInfo();
1268                    if (info != null && info.isConnected()) {
1269                        sendConnectedBroadcast(info);
1270                    }
1271                }
1272            }
1273        }
1274    };
1275
1276    @Override
1277    public void setPolicyDataEnable(int networkType, boolean enabled) {
1278        // only someone like NPMS should only be calling us
1279        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1280
1281        mHandler.sendMessage(mHandler.obtainMessage(
1282                EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1283    }
1284
1285    private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1286   // TODO - handle this passing to factories
1287//        if (isNetworkTypeValid(networkType)) {
1288//            final NetworkStateTracker tracker = mNetTrackers[networkType];
1289//            if (tracker != null) {
1290//                tracker.setPolicyDataEnable(enabled);
1291//            }
1292//        }
1293    }
1294
1295    private void enforceAccessPermission() {
1296        mContext.enforceCallingOrSelfPermission(
1297                android.Manifest.permission.ACCESS_NETWORK_STATE,
1298                "ConnectivityService");
1299    }
1300
1301    private void enforceChangePermission() {
1302        mContext.enforceCallingOrSelfPermission(
1303                android.Manifest.permission.CHANGE_NETWORK_STATE,
1304                "ConnectivityService");
1305    }
1306
1307    // TODO Make this a special check when it goes public
1308    private void enforceTetherChangePermission() {
1309        mContext.enforceCallingOrSelfPermission(
1310                android.Manifest.permission.CHANGE_NETWORK_STATE,
1311                "ConnectivityService");
1312    }
1313
1314    private void enforceTetherAccessPermission() {
1315        mContext.enforceCallingOrSelfPermission(
1316                android.Manifest.permission.ACCESS_NETWORK_STATE,
1317                "ConnectivityService");
1318    }
1319
1320    private void enforceConnectivityInternalPermission() {
1321        mContext.enforceCallingOrSelfPermission(
1322                android.Manifest.permission.CONNECTIVITY_INTERNAL,
1323                "ConnectivityService");
1324    }
1325
1326    public void sendConnectedBroadcast(NetworkInfo info) {
1327        enforceConnectivityInternalPermission();
1328        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1329        sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
1330    }
1331
1332    private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
1333        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1334        sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
1335    }
1336
1337    private void sendInetConditionBroadcast(NetworkInfo info) {
1338        sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1339    }
1340
1341    private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
1342        if (mLockdownTracker != null) {
1343            info = mLockdownTracker.augmentNetworkInfo(info);
1344        }
1345
1346        Intent intent = new Intent(bcastType);
1347        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1348        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1349        if (info.isFailover()) {
1350            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1351            info.setFailover(false);
1352        }
1353        if (info.getReason() != null) {
1354            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1355        }
1356        if (info.getExtraInfo() != null) {
1357            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1358                    info.getExtraInfo());
1359        }
1360        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1361        return intent;
1362    }
1363
1364    private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1365        sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1366    }
1367
1368    private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1369        sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
1370    }
1371
1372    private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
1373        Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1374        intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1375        intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
1376        intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
1377        final long ident = Binder.clearCallingIdentity();
1378        try {
1379            mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1380                    RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1381        } finally {
1382            Binder.restoreCallingIdentity(ident);
1383        }
1384    }
1385
1386    private void sendStickyBroadcast(Intent intent) {
1387        synchronized(this) {
1388            if (!mSystemReady) {
1389                mInitialBroadcast = new Intent(intent);
1390            }
1391            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1392            if (VDBG) {
1393                log("sendStickyBroadcast: action=" + intent.getAction());
1394            }
1395
1396            final long ident = Binder.clearCallingIdentity();
1397            try {
1398                mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1399            } finally {
1400                Binder.restoreCallingIdentity(ident);
1401            }
1402        }
1403    }
1404
1405    private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1406        if (delayMs <= 0) {
1407            sendStickyBroadcast(intent);
1408        } else {
1409            if (VDBG) {
1410                log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1411                        + intent.getAction());
1412            }
1413            mHandler.sendMessageDelayed(mHandler.obtainMessage(
1414                    EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1415        }
1416    }
1417
1418    void systemReady() {
1419        // start network sampling ..
1420        Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
1421        intent.setPackage(mContext.getPackageName());
1422
1423        mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
1424                SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
1425        setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
1426
1427        loadGlobalProxy();
1428
1429        synchronized(this) {
1430            mSystemReady = true;
1431            if (mInitialBroadcast != null) {
1432                mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
1433                mInitialBroadcast = null;
1434            }
1435        }
1436        // load the global proxy at startup
1437        mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
1438
1439        // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1440        // for user to unlock device.
1441        if (!updateLockdownVpn()) {
1442            final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1443            mContext.registerReceiver(mUserPresentReceiver, filter);
1444        }
1445
1446        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
1447    }
1448
1449    private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1450        @Override
1451        public void onReceive(Context context, Intent intent) {
1452            // Try creating lockdown tracker, since user present usually means
1453            // unlocked keystore.
1454            if (updateLockdownVpn()) {
1455                mContext.unregisterReceiver(this);
1456            }
1457        }
1458    };
1459
1460    /** @hide */
1461    @Override
1462    public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1463        enforceConnectivityInternalPermission();
1464        if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
1465//        mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
1466    }
1467
1468    /**
1469     * Setup data activity tracking for the given network.
1470     *
1471     * Every {@code setupDataActivityTracking} should be paired with a
1472     * {@link #removeDataActivityTracking} for cleanup.
1473     */
1474    private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1475        final String iface = networkAgent.linkProperties.getInterfaceName();
1476
1477        final int timeout;
1478        int type = ConnectivityManager.TYPE_NONE;
1479
1480        if (networkAgent.networkCapabilities.hasTransport(
1481                NetworkCapabilities.TRANSPORT_CELLULAR)) {
1482            timeout = Settings.Global.getInt(mContext.getContentResolver(),
1483                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
1484                                             5);
1485            type = ConnectivityManager.TYPE_MOBILE;
1486        } else if (networkAgent.networkCapabilities.hasTransport(
1487                NetworkCapabilities.TRANSPORT_WIFI)) {
1488            timeout = Settings.Global.getInt(mContext.getContentResolver(),
1489                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
1490                                             0);
1491            type = ConnectivityManager.TYPE_WIFI;
1492        } else {
1493            // do not track any other networks
1494            timeout = 0;
1495        }
1496
1497        if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
1498            try {
1499                mNetd.addIdleTimer(iface, timeout, type);
1500            } catch (Exception e) {
1501                // You shall not crash!
1502                loge("Exception in setupDataActivityTracking " + e);
1503            }
1504        }
1505    }
1506
1507    /**
1508     * Remove data activity tracking when network disconnects.
1509     */
1510    private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1511        final String iface = networkAgent.linkProperties.getInterfaceName();
1512        final NetworkCapabilities caps = networkAgent.networkCapabilities;
1513
1514        if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1515                              caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
1516            try {
1517                // the call fails silently if no idletimer setup for this interface
1518                mNetd.removeIdleTimer(iface);
1519            } catch (Exception e) {
1520                loge("Exception in removeDataActivityTracking " + e);
1521            }
1522        }
1523    }
1524
1525    /**
1526     * Reads the network specific MTU size from reources.
1527     * and set it on it's iface.
1528     */
1529    private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1530        final String iface = newLp.getInterfaceName();
1531        final int mtu = newLp.getMtu();
1532        if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1533            if (VDBG) log("identical MTU - not setting");
1534            return;
1535        }
1536
1537        if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
1538            loge("Unexpected mtu value: " + mtu + ", " + iface);
1539            return;
1540        }
1541
1542        // Cannot set MTU without interface name
1543        if (TextUtils.isEmpty(iface)) {
1544            loge("Setting MTU size with null iface.");
1545            return;
1546        }
1547
1548        try {
1549            if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
1550            mNetd.setMtu(iface, mtu);
1551        } catch (Exception e) {
1552            Slog.e(TAG, "exception in setMtu()" + e);
1553        }
1554    }
1555
1556    /**
1557     * Reads the network specific TCP buffer sizes from SystemProperties
1558     * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1559     * wide use
1560     */
1561    private void updateNetworkSettings(NetworkStateTracker nt) {
1562        String key = nt.getTcpBufferSizesPropName();
1563        String bufferSizes = key == null ? null : SystemProperties.get(key);
1564
1565        if (TextUtils.isEmpty(bufferSizes)) {
1566            if (VDBG) log(key + " not found in system properties. Using defaults");
1567
1568            // Setting to default values so we won't be stuck to previous values
1569            key = "net.tcp.buffersize.default";
1570            bufferSizes = SystemProperties.get(key);
1571        }
1572
1573        // Set values in kernel
1574        if (bufferSizes.length() != 0) {
1575            if (VDBG) {
1576                log("Setting TCP values: [" + bufferSizes
1577                        + "] which comes from [" + key + "]");
1578            }
1579            setBufferSize(bufferSizes);
1580        }
1581
1582        final String defaultRwndKey = "net.tcp.default_init_rwnd";
1583        int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
1584        Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1585            Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
1586        final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1587        if (rwndValue != 0) {
1588            SystemProperties.set(sysctlKey, rwndValue.toString());
1589        }
1590    }
1591
1592    /**
1593     * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1594     * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1595     *
1596     * @param bufferSizes in the format of "readMin, readInitial, readMax,
1597     *        writeMin, writeInitial, writeMax"
1598     */
1599    private void setBufferSize(String bufferSizes) {
1600        try {
1601            String[] values = bufferSizes.split(",");
1602
1603            if (values.length == 6) {
1604              final String prefix = "/sys/kernel/ipv4/tcp_";
1605                FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1606                FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1607                FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1608                FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1609                FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1610                FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1611            } else {
1612                loge("Invalid buffersize string: " + bufferSizes);
1613            }
1614        } catch (IOException e) {
1615            loge("Can't set tcp buffer sizes:" + e);
1616        }
1617    }
1618
1619    private void flushVmDnsCache() {
1620        /*
1621         * Tell the VMs to toss their DNS caches
1622         */
1623        Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1624        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1625        /*
1626         * Connectivity events can happen before boot has completed ...
1627         */
1628        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1629        final long ident = Binder.clearCallingIdentity();
1630        try {
1631            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1632        } finally {
1633            Binder.restoreCallingIdentity(ident);
1634        }
1635    }
1636
1637    @Override
1638    public int getRestoreDefaultNetworkDelay(int networkType) {
1639        String restoreDefaultNetworkDelayStr = SystemProperties.get(
1640                NETWORK_RESTORE_DELAY_PROP_NAME);
1641        if(restoreDefaultNetworkDelayStr != null &&
1642                restoreDefaultNetworkDelayStr.length() != 0) {
1643            try {
1644                return Integer.valueOf(restoreDefaultNetworkDelayStr);
1645            } catch (NumberFormatException e) {
1646            }
1647        }
1648        // if the system property isn't set, use the value for the apn type
1649        int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1650
1651        if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1652                (mNetConfigs[networkType] != null)) {
1653            ret = mNetConfigs[networkType].restoreTime;
1654        }
1655        return ret;
1656    }
1657
1658    @Override
1659    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1660        final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
1661        if (mContext.checkCallingOrSelfPermission(
1662                android.Manifest.permission.DUMP)
1663                != PackageManager.PERMISSION_GRANTED) {
1664            pw.println("Permission Denial: can't dump ConnectivityService " +
1665                    "from from pid=" + Binder.getCallingPid() + ", uid=" +
1666                    Binder.getCallingUid());
1667            return;
1668        }
1669
1670        pw.println("NetworkFactories for:");
1671        pw.increaseIndent();
1672        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1673            pw.println(nfi.name);
1674        }
1675        pw.decreaseIndent();
1676        pw.println();
1677
1678        NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1679        pw.print("Active default network: ");
1680        if (defaultNai == null) {
1681            pw.println("none");
1682        } else {
1683            pw.println(defaultNai.network.netId);
1684        }
1685        pw.println();
1686
1687        pw.println("Current Networks:");
1688        pw.increaseIndent();
1689        for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1690            pw.println(nai.toString());
1691            pw.increaseIndent();
1692            pw.println("Requests:");
1693            pw.increaseIndent();
1694            for (int i = 0; i < nai.networkRequests.size(); i++) {
1695                pw.println(nai.networkRequests.valueAt(i).toString());
1696            }
1697            pw.decreaseIndent();
1698            pw.println("Lingered:");
1699            pw.increaseIndent();
1700            for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1701            pw.decreaseIndent();
1702            pw.decreaseIndent();
1703        }
1704        pw.decreaseIndent();
1705        pw.println();
1706
1707        pw.println("Network Requests:");
1708        pw.increaseIndent();
1709        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1710            pw.println(nri.toString());
1711        }
1712        pw.println();
1713        pw.decreaseIndent();
1714
1715        pw.print("mActiveDefaultNetwork: " + mActiveDefaultNetwork);
1716        if (mActiveDefaultNetwork != TYPE_NONE) {
1717            NetworkInfo activeNetworkInfo = getActiveNetworkInfo();
1718            if (activeNetworkInfo != null) {
1719                pw.print(" " + activeNetworkInfo.getState() +
1720                         "/" + activeNetworkInfo.getDetailedState());
1721            }
1722        }
1723        pw.println();
1724
1725        pw.println("mLegacyTypeTracker:");
1726        pw.increaseIndent();
1727        mLegacyTypeTracker.dump(pw);
1728        pw.decreaseIndent();
1729        pw.println();
1730
1731        synchronized (this) {
1732            pw.println("NetworkTranstionWakeLock is currently " +
1733                    (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1734            pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1735        }
1736        pw.println();
1737
1738        mTethering.dump(fd, pw, args);
1739
1740        if (mInetLog != null) {
1741            pw.println();
1742            pw.println("Inet condition reports:");
1743            pw.increaseIndent();
1744            for(int i = 0; i < mInetLog.size(); i++) {
1745                pw.println(mInetLog.get(i));
1746            }
1747            pw.decreaseIndent();
1748        }
1749    }
1750
1751    // must be stateless - things change under us.
1752    private class NetworkStateTrackerHandler extends Handler {
1753        public NetworkStateTrackerHandler(Looper looper) {
1754            super(looper);
1755        }
1756
1757        @Override
1758        public void handleMessage(Message msg) {
1759            NetworkInfo info;
1760            switch (msg.what) {
1761                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
1762                    handleAsyncChannelHalfConnect(msg);
1763                    break;
1764                }
1765                case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1766                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1767                    if (nai != null) nai.asyncChannel.disconnect();
1768                    break;
1769                }
1770                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1771                    handleAsyncChannelDisconnected(msg);
1772                    break;
1773                }
1774                case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1775                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1776                    if (nai == null) {
1777                        loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1778                    } else {
1779                        updateCapabilities(nai, (NetworkCapabilities)msg.obj);
1780                    }
1781                    break;
1782                }
1783                case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1784                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1785                    if (nai == null) {
1786                        loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1787                    } else {
1788                        if (VDBG) {
1789                            log("Update of Linkproperties for " + nai.name() +
1790                                    "; created=" + nai.created);
1791                        }
1792                        LinkProperties oldLp = nai.linkProperties;
1793                        synchronized (nai) {
1794                            nai.linkProperties = (LinkProperties)msg.obj;
1795                        }
1796                        if (nai.created) updateLinkProperties(nai, oldLp);
1797                    }
1798                    break;
1799                }
1800                case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1801                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1802                    if (nai == null) {
1803                        loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1804                        break;
1805                    }
1806                    info = (NetworkInfo) msg.obj;
1807                    updateNetworkInfo(nai, info);
1808                    break;
1809                }
1810                case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1811                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1812                    if (nai == null) {
1813                        loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1814                        break;
1815                    }
1816                    Integer score = (Integer) msg.obj;
1817                    if (score != null) updateNetworkScore(nai, score.intValue());
1818                    break;
1819                }
1820                case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1821                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1822                    if (nai == null) {
1823                        loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1824                        break;
1825                    }
1826                    try {
1827                        mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
1828                    } catch (Exception e) {
1829                        // Never crash!
1830                        loge("Exception in addVpnUidRanges: " + e);
1831                    }
1832                    break;
1833                }
1834                case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1835                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1836                    if (nai == null) {
1837                        loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1838                        break;
1839                    }
1840                    try {
1841                        mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
1842                    } catch (Exception e) {
1843                        // Never crash!
1844                        loge("Exception in removeVpnUidRanges: " + e);
1845                    }
1846                    break;
1847                }
1848                case NetworkAgent.EVENT_BLOCK_ADDRESS_FAMILY: {
1849                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1850                    if (nai == null) {
1851                        loge("EVENT_BLOCK_ADDRESS_FAMILY from unknown NetworkAgent");
1852                        break;
1853                    }
1854                    try {
1855                        mNetd.blockAddressFamily((Integer) msg.obj, nai.network.netId,
1856                                nai.linkProperties.getInterfaceName());
1857                    } catch (Exception e) {
1858                        // Never crash!
1859                        loge("Exception in blockAddressFamily: " + e);
1860                    }
1861                    break;
1862                }
1863                case NetworkAgent.EVENT_UNBLOCK_ADDRESS_FAMILY: {
1864                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1865                    if (nai == null) {
1866                        loge("EVENT_UNBLOCK_ADDRESS_FAMILY from unknown NetworkAgent");
1867                        break;
1868                    }
1869                    try {
1870                        mNetd.unblockAddressFamily((Integer) msg.obj, nai.network.netId,
1871                                nai.linkProperties.getInterfaceName());
1872                    } catch (Exception e) {
1873                        // Never crash!
1874                        loge("Exception in blockAddressFamily: " + e);
1875                    }
1876                    break;
1877                }
1878                case NetworkMonitor.EVENT_NETWORK_VALIDATED: {
1879                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
1880                    handleConnectionValidated(nai);
1881                    break;
1882                }
1883                case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
1884                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
1885                    handleLingerComplete(nai);
1886                    break;
1887                }
1888                case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
1889                    if (msg.arg1 == 0) {
1890                        setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
1891                    } else {
1892                        NetworkAgentInfo nai = mNetworkForNetId.get(msg.arg2);
1893                        if (nai == null) {
1894                            loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
1895                            break;
1896                        }
1897                        setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
1898                                nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
1899                    }
1900                    break;
1901                }
1902                case NetworkStateTracker.EVENT_STATE_CHANGED: {
1903                    info = (NetworkInfo) msg.obj;
1904                    NetworkInfo.State state = info.getState();
1905
1906                    if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
1907                            (state == NetworkInfo.State.DISCONNECTED) ||
1908                            (state == NetworkInfo.State.SUSPENDED)) {
1909                        log("ConnectivityChange for " +
1910                            info.getTypeName() + ": " +
1911                            state + "/" + info.getDetailedState());
1912                    }
1913
1914                    // Since mobile has the notion of a network/apn that can be used for
1915                    // provisioning we need to check every time we're connected as
1916                    // CaptiveProtalTracker won't detected it because DCT doesn't report it
1917                    // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
1918                    // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
1919                    // is received by MDST and sent here as EVENT_STATE_CHANGED.
1920                    if (ConnectivityManager.isNetworkTypeMobile(info.getType())
1921                            && (0 != Settings.Global.getInt(mContext.getContentResolver(),
1922                                        Settings.Global.DEVICE_PROVISIONED, 0))
1923                            && (((state == NetworkInfo.State.CONNECTED)
1924                                    && (info.getType() == ConnectivityManager.TYPE_MOBILE))
1925                                || info.isConnectedToProvisioningNetwork())) {
1926                        log("ConnectivityChange checkMobileProvisioning for"
1927                                + " TYPE_MOBILE or ProvisioningNetwork");
1928                        checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
1929                    }
1930
1931                    EventLogTags.writeConnectivityStateChanged(
1932                            info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
1933
1934                    if (info.isConnectedToProvisioningNetwork()) {
1935                        /**
1936                         * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
1937                         * for now its an in between network, its a network that
1938                         * is actually a default network but we don't want it to be
1939                         * announced as such to keep background applications from
1940                         * trying to use it. It turns out that some still try so we
1941                         * take the additional step of clearing any default routes
1942                         * to the link that may have incorrectly setup by the lower
1943                         * levels.
1944                         */
1945                        LinkProperties lp = getLinkPropertiesForTypeInternal(info.getType());
1946                        if (DBG) {
1947                            log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
1948                        }
1949
1950                        // Clear any default routes setup by the radio so
1951                        // any activity by applications trying to use this
1952                        // connection will fail until the provisioning network
1953                        // is enabled.
1954                        /*
1955                        for (RouteInfo r : lp.getRoutes()) {
1956                            removeRoute(lp, r, TO_DEFAULT_TABLE,
1957                                        mNetTrackers[info.getType()].getNetwork().netId);
1958                        }
1959                        */
1960                    } else if (state == NetworkInfo.State.DISCONNECTED) {
1961                    } else if (state == NetworkInfo.State.SUSPENDED) {
1962                    } else if (state == NetworkInfo.State.CONNECTED) {
1963                    //    handleConnect(info);
1964                    }
1965                    if (mLockdownTracker != null) {
1966                        mLockdownTracker.onNetworkInfoChanged(info);
1967                    }
1968                    break;
1969                }
1970                case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
1971                    info = (NetworkInfo) msg.obj;
1972                    // TODO: Temporary allowing network configuration
1973                    //       change not resetting sockets.
1974                    //       @see bug/4455071
1975                    /*
1976                    handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()],
1977                            false);
1978                    */
1979                    break;
1980                }
1981                case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
1982                    info = (NetworkInfo) msg.obj;
1983                    int type = info.getType();
1984                    if (mNetConfigs[type].isDefault()) updateNetworkSettings(mNetTrackers[type]);
1985                    break;
1986                }
1987            }
1988        }
1989    }
1990
1991    private void handleAsyncChannelHalfConnect(Message msg) {
1992        AsyncChannel ac = (AsyncChannel) msg.obj;
1993        if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
1994            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
1995                if (VDBG) log("NetworkFactory connected");
1996                // A network factory has connected.  Send it all current NetworkRequests.
1997                for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1998                    if (nri.isRequest == false) continue;
1999                    NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2000                    ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
2001                            (nai != null ? nai.currentScore : 0), 0, nri.request);
2002                }
2003            } else {
2004                loge("Error connecting NetworkFactory");
2005                mNetworkFactoryInfos.remove(msg.obj);
2006            }
2007        } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2008            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2009                if (VDBG) log("NetworkAgent connected");
2010                // A network agent has requested a connection.  Establish the connection.
2011                mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2012                        sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2013            } else {
2014                loge("Error connecting NetworkAgent");
2015                NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
2016                if (nai != null) {
2017                    synchronized (mNetworkForNetId) {
2018                        mNetworkForNetId.remove(nai.network.netId);
2019                    }
2020                    // Just in case.
2021                    mLegacyTypeTracker.remove(nai);
2022                }
2023            }
2024        }
2025    }
2026    private void handleAsyncChannelDisconnected(Message msg) {
2027        NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2028        if (nai != null) {
2029            if (DBG) {
2030                log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2031            }
2032            // A network agent has disconnected.
2033            if (nai.created) {
2034                // Tell netd to clean up the configuration for this network
2035                // (routing rules, DNS, etc).
2036                try {
2037                    mNetd.removeNetwork(nai.network.netId);
2038                } catch (Exception e) {
2039                    loge("Exception removing network: " + e);
2040                }
2041            }
2042            // TODO - if we move the logic to the network agent (have them disconnect
2043            // because they lost all their requests or because their score isn't good)
2044            // then they would disconnect organically, report their new state and then
2045            // disconnect the channel.
2046            if (nai.networkInfo.isConnected()) {
2047                nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2048                        null, null);
2049            }
2050            if (isDefaultNetwork(nai)) {
2051                mDefaultInetConditionPublished = 0;
2052            }
2053            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2054            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2055            mNetworkAgentInfos.remove(msg.replyTo);
2056            updateClat(null, nai.linkProperties, nai);
2057            mLegacyTypeTracker.remove(nai);
2058            synchronized (mNetworkForNetId) {
2059                mNetworkForNetId.remove(nai.network.netId);
2060            }
2061            // Since we've lost the network, go through all the requests that
2062            // it was satisfying and see if any other factory can satisfy them.
2063            final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
2064            for (int i = 0; i < nai.networkRequests.size(); i++) {
2065                NetworkRequest request = nai.networkRequests.valueAt(i);
2066                NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2067                if (VDBG) {
2068                    log(" checking request " + request + ", currentNetwork = " +
2069                            (currentNetwork != null ? currentNetwork.name() : "null"));
2070                }
2071                if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2072                    mNetworkForRequestId.remove(request.requestId);
2073                    sendUpdatedScoreToFactories(request, 0);
2074                    NetworkAgentInfo alternative = null;
2075                    for (Map.Entry entry : mNetworkAgentInfos.entrySet()) {
2076                        NetworkAgentInfo existing = (NetworkAgentInfo)entry.getValue();
2077                        if (existing.networkInfo.isConnected() &&
2078                                request.networkCapabilities.satisfiedByNetworkCapabilities(
2079                                existing.networkCapabilities) &&
2080                                (alternative == null ||
2081                                 alternative.currentScore < existing.currentScore)) {
2082                            alternative = existing;
2083                        }
2084                    }
2085                    if (alternative != null && !toActivate.contains(alternative)) {
2086                        toActivate.add(alternative);
2087                    }
2088                }
2089            }
2090            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2091                removeDataActivityTracking(nai);
2092                mActiveDefaultNetwork = ConnectivityManager.TYPE_NONE;
2093                requestNetworkTransitionWakelock(nai.name());
2094            }
2095            for (NetworkAgentInfo networkToActivate : toActivate) {
2096                networkToActivate.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2097            }
2098        }
2099    }
2100
2101    private void handleRegisterNetworkRequest(Message msg) {
2102        final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2103        final NetworkCapabilities newCap = nri.request.networkCapabilities;
2104        int score = 0;
2105
2106        // Check for the best currently alive network that satisfies this request
2107        NetworkAgentInfo bestNetwork = null;
2108        for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
2109            if (VDBG) log("handleRegisterNetworkRequest checking " + network.name());
2110            if (newCap.satisfiedByNetworkCapabilities(network.networkCapabilities)) {
2111                if (VDBG) log("apparently satisfied.  currentScore=" + network.currentScore);
2112                if ((bestNetwork == null) || bestNetwork.currentScore < network.currentScore) {
2113                    bestNetwork = network;
2114                }
2115            }
2116        }
2117        if (bestNetwork != null) {
2118            if (VDBG) log("using " + bestNetwork.name());
2119            if (nri.isRequest && bestNetwork.networkInfo.isConnected()) {
2120                // Cancel any lingering so the linger timeout doesn't teardown this network
2121                // even though we have a request for it.
2122                bestNetwork.networkLingered.clear();
2123                bestNetwork.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2124            }
2125            bestNetwork.addRequest(nri.request);
2126            mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
2127            notifyNetworkCallback(bestNetwork, nri);
2128            score = bestNetwork.currentScore;
2129            if (nri.isRequest && nri.request.legacyType != TYPE_NONE) {
2130                mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2131            }
2132        }
2133        mNetworkRequests.put(nri.request, nri);
2134        if (nri.isRequest) {
2135            if (DBG) log("sending new NetworkRequest to factories");
2136            for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2137                nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
2138                        0, nri.request);
2139            }
2140        }
2141    }
2142
2143    private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2144        NetworkRequestInfo nri = mNetworkRequests.get(request);
2145        if (nri != null) {
2146            if (nri.mUid != callingUid) {
2147                if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2148                return;
2149            }
2150            if (DBG) log("releasing NetworkRequest " + request);
2151            nri.unlinkDeathRecipient();
2152            mNetworkRequests.remove(request);
2153            // tell the network currently servicing this that it's no longer interested
2154            NetworkAgentInfo affectedNetwork = mNetworkForRequestId.get(nri.request.requestId);
2155            if (affectedNetwork != null) {
2156                mNetworkForRequestId.remove(nri.request.requestId);
2157                affectedNetwork.networkRequests.remove(nri.request.requestId);
2158                if (VDBG) {
2159                    log(" Removing from current network " + affectedNetwork.name() + ", leaving " +
2160                            affectedNetwork.networkRequests.size() + " requests.");
2161                }
2162                if (nri.isRequest && nri.request.legacyType != TYPE_NONE) {
2163                    mLegacyTypeTracker.remove(nri.request.legacyType, affectedNetwork);
2164                }
2165            }
2166
2167            if (nri.isRequest) {
2168                for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2169                    nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2170                            nri.request);
2171                }
2172
2173                if (affectedNetwork != null) {
2174                    // check if this network still has live requests - otherwise, tear down
2175                    // TODO - probably push this to the NF/NA
2176                    boolean keep = affectedNetwork.isVPN();
2177                    for (int i = 0; i < affectedNetwork.networkRequests.size() && !keep; i++) {
2178                        NetworkRequest r = affectedNetwork.networkRequests.valueAt(i);
2179                        if (mNetworkRequests.get(r).isRequest) {
2180                            keep = true;
2181                        }
2182                    }
2183                    if (keep == false) {
2184                        if (DBG) log("no live requests for " + affectedNetwork.name() +
2185                                "; disconnecting");
2186                        affectedNetwork.asyncChannel.disconnect();
2187                    }
2188                }
2189            }
2190            callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2191        }
2192    }
2193
2194    private class InternalHandler extends Handler {
2195        public InternalHandler(Looper looper) {
2196            super(looper);
2197        }
2198
2199        @Override
2200        public void handleMessage(Message msg) {
2201            NetworkInfo info;
2202            switch (msg.what) {
2203                case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
2204                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
2205                    String causedBy = null;
2206                    synchronized (ConnectivityService.this) {
2207                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2208                                mNetTransitionWakeLock.isHeld()) {
2209                            mNetTransitionWakeLock.release();
2210                            causedBy = mNetTransitionWakeLockCausedBy;
2211                        } else {
2212                            break;
2213                        }
2214                    }
2215                    if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2216                        log("Failed to find a new network - expiring NetTransition Wakelock");
2217                    } else {
2218                        log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2219                                " cleared because we found a replacement network");
2220                    }
2221                    break;
2222                }
2223                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
2224                    handleDeprecatedGlobalHttpProxy();
2225                    break;
2226                }
2227                case EVENT_SET_DEPENDENCY_MET: {
2228                    boolean met = (msg.arg1 == ENABLED);
2229                    handleSetDependencyMet(msg.arg2, met);
2230                    break;
2231                }
2232                case EVENT_SEND_STICKY_BROADCAST_INTENT: {
2233                    Intent intent = (Intent)msg.obj;
2234                    sendStickyBroadcast(intent);
2235                    break;
2236                }
2237                case EVENT_SET_POLICY_DATA_ENABLE: {
2238                    final int networkType = msg.arg1;
2239                    final boolean enabled = msg.arg2 == ENABLED;
2240                    handleSetPolicyDataEnable(networkType, enabled);
2241                    break;
2242                }
2243                case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2244                    int tag = mEnableFailFastMobileDataTag.get();
2245                    if (msg.arg1 == tag) {
2246                        MobileDataStateTracker mobileDst =
2247                            (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2248                        if (mobileDst != null) {
2249                            mobileDst.setEnableFailFastMobileData(msg.arg2);
2250                        }
2251                    } else {
2252                        log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2253                                + " != tag:" + tag);
2254                    }
2255                    break;
2256                }
2257                case EVENT_SAMPLE_INTERVAL_ELAPSED: {
2258                    handleNetworkSamplingTimeout();
2259                    break;
2260                }
2261                case EVENT_PROXY_HAS_CHANGED: {
2262                    handleApplyDefaultProxy((ProxyInfo)msg.obj);
2263                    break;
2264                }
2265                case EVENT_REGISTER_NETWORK_FACTORY: {
2266                    handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2267                    break;
2268                }
2269                case EVENT_UNREGISTER_NETWORK_FACTORY: {
2270                    handleUnregisterNetworkFactory((Messenger)msg.obj);
2271                    break;
2272                }
2273                case EVENT_REGISTER_NETWORK_AGENT: {
2274                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2275                    break;
2276                }
2277                case EVENT_REGISTER_NETWORK_REQUEST:
2278                case EVENT_REGISTER_NETWORK_LISTENER: {
2279                    handleRegisterNetworkRequest(msg);
2280                    break;
2281                }
2282                case EVENT_RELEASE_NETWORK_REQUEST: {
2283                    handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
2284                    break;
2285                }
2286                case EVENT_SYSTEM_READY: {
2287                    for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2288                        nai.networkMonitor.systemReady = true;
2289                    }
2290                    break;
2291                }
2292            }
2293        }
2294    }
2295
2296    // javadoc from interface
2297    public int tether(String iface) {
2298        enforceTetherChangePermission();
2299
2300        if (isTetheringSupported()) {
2301            return mTethering.tether(iface);
2302        } else {
2303            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2304        }
2305    }
2306
2307    // javadoc from interface
2308    public int untether(String iface) {
2309        enforceTetherChangePermission();
2310
2311        if (isTetheringSupported()) {
2312            return mTethering.untether(iface);
2313        } else {
2314            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2315        }
2316    }
2317
2318    // javadoc from interface
2319    public int getLastTetherError(String iface) {
2320        enforceTetherAccessPermission();
2321
2322        if (isTetheringSupported()) {
2323            return mTethering.getLastTetherError(iface);
2324        } else {
2325            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2326        }
2327    }
2328
2329    // TODO - proper iface API for selection by property, inspection, etc
2330    public String[] getTetherableUsbRegexs() {
2331        enforceTetherAccessPermission();
2332        if (isTetheringSupported()) {
2333            return mTethering.getTetherableUsbRegexs();
2334        } else {
2335            return new String[0];
2336        }
2337    }
2338
2339    public String[] getTetherableWifiRegexs() {
2340        enforceTetherAccessPermission();
2341        if (isTetheringSupported()) {
2342            return mTethering.getTetherableWifiRegexs();
2343        } else {
2344            return new String[0];
2345        }
2346    }
2347
2348    public String[] getTetherableBluetoothRegexs() {
2349        enforceTetherAccessPermission();
2350        if (isTetheringSupported()) {
2351            return mTethering.getTetherableBluetoothRegexs();
2352        } else {
2353            return new String[0];
2354        }
2355    }
2356
2357    public int setUsbTethering(boolean enable) {
2358        enforceTetherChangePermission();
2359        if (isTetheringSupported()) {
2360            return mTethering.setUsbTethering(enable);
2361        } else {
2362            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2363        }
2364    }
2365
2366    // TODO - move iface listing, queries, etc to new module
2367    // javadoc from interface
2368    public String[] getTetherableIfaces() {
2369        enforceTetherAccessPermission();
2370        return mTethering.getTetherableIfaces();
2371    }
2372
2373    public String[] getTetheredIfaces() {
2374        enforceTetherAccessPermission();
2375        return mTethering.getTetheredIfaces();
2376    }
2377
2378    public String[] getTetheringErroredIfaces() {
2379        enforceTetherAccessPermission();
2380        return mTethering.getErroredIfaces();
2381    }
2382
2383    public String[] getTetheredDhcpRanges() {
2384        enforceConnectivityInternalPermission();
2385        return mTethering.getTetheredDhcpRanges();
2386    }
2387
2388    // if ro.tether.denied = true we default to no tethering
2389    // gservices could set the secure setting to 1 though to enable it on a build where it
2390    // had previously been turned off.
2391    public boolean isTetheringSupported() {
2392        enforceTetherAccessPermission();
2393        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2394        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2395                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2396                && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
2397        return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2398                mTethering.getTetherableWifiRegexs().length != 0 ||
2399                mTethering.getTetherableBluetoothRegexs().length != 0) &&
2400                mTethering.getUpstreamIfaceTypes().length != 0);
2401    }
2402
2403    // Called when we lose the default network and have no replacement yet.
2404    // This will automatically be cleared after X seconds or a new default network
2405    // becomes CONNECTED, whichever happens first.  The timer is started by the
2406    // first caller and not restarted by subsequent callers.
2407    private void requestNetworkTransitionWakelock(String forWhom) {
2408        int serialNum = 0;
2409        synchronized (this) {
2410            if (mNetTransitionWakeLock.isHeld()) return;
2411            serialNum = ++mNetTransitionWakeLockSerialNumber;
2412            mNetTransitionWakeLock.acquire();
2413            mNetTransitionWakeLockCausedBy = forWhom;
2414        }
2415        mHandler.sendMessageDelayed(mHandler.obtainMessage(
2416                EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
2417                mNetTransitionWakeLockTimeout);
2418        return;
2419    }
2420
2421    // 100 percent is full good, 0 is full bad.
2422    public void reportInetCondition(int networkType, int percentage) {
2423        if (percentage > 50) return;  // don't handle good network reports
2424        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2425        if (nai != null) reportBadNetwork(nai.network);
2426    }
2427
2428    public void reportBadNetwork(Network network) {
2429        //TODO
2430    }
2431
2432    public ProxyInfo getProxy() {
2433        // this information is already available as a world read/writable jvm property
2434        // so this API change wouldn't have a benifit.  It also breaks the passing
2435        // of proxy info to all the JVMs.
2436        // enforceAccessPermission();
2437        synchronized (mProxyLock) {
2438            ProxyInfo ret = mGlobalProxy;
2439            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2440            return ret;
2441        }
2442    }
2443
2444    public void setGlobalProxy(ProxyInfo proxyProperties) {
2445        enforceConnectivityInternalPermission();
2446
2447        synchronized (mProxyLock) {
2448            if (proxyProperties == mGlobalProxy) return;
2449            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2450            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2451
2452            String host = "";
2453            int port = 0;
2454            String exclList = "";
2455            String pacFileUrl = "";
2456            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
2457                    (proxyProperties.getPacFileUrl() != null))) {
2458                if (!proxyProperties.isValid()) {
2459                    if (DBG)
2460                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2461                    return;
2462                }
2463                mGlobalProxy = new ProxyInfo(proxyProperties);
2464                host = mGlobalProxy.getHost();
2465                port = mGlobalProxy.getPort();
2466                exclList = mGlobalProxy.getExclusionListAsString();
2467                if (proxyProperties.getPacFileUrl() != null) {
2468                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
2469                }
2470            } else {
2471                mGlobalProxy = null;
2472            }
2473            ContentResolver res = mContext.getContentResolver();
2474            final long token = Binder.clearCallingIdentity();
2475            try {
2476                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2477                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2478                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2479                        exclList);
2480                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
2481            } finally {
2482                Binder.restoreCallingIdentity(token);
2483            }
2484        }
2485
2486        if (mGlobalProxy == null) {
2487            proxyProperties = mDefaultProxy;
2488        }
2489        sendProxyBroadcast(proxyProperties);
2490    }
2491
2492    private void loadGlobalProxy() {
2493        ContentResolver res = mContext.getContentResolver();
2494        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2495        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2496        String exclList = Settings.Global.getString(res,
2497                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2498        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2499        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
2500            ProxyInfo proxyProperties;
2501            if (!TextUtils.isEmpty(pacFileUrl)) {
2502                proxyProperties = new ProxyInfo(pacFileUrl);
2503            } else {
2504                proxyProperties = new ProxyInfo(host, port, exclList);
2505            }
2506            if (!proxyProperties.isValid()) {
2507                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2508                return;
2509            }
2510
2511            synchronized (mProxyLock) {
2512                mGlobalProxy = proxyProperties;
2513            }
2514        }
2515    }
2516
2517    public ProxyInfo getGlobalProxy() {
2518        // this information is already available as a world read/writable jvm property
2519        // so this API change wouldn't have a benifit.  It also breaks the passing
2520        // of proxy info to all the JVMs.
2521        // enforceAccessPermission();
2522        synchronized (mProxyLock) {
2523            return mGlobalProxy;
2524        }
2525    }
2526
2527    private void handleApplyDefaultProxy(ProxyInfo proxy) {
2528        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2529                && (proxy.getPacFileUrl() == null)) {
2530            proxy = null;
2531        }
2532        synchronized (mProxyLock) {
2533            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2534            if (mDefaultProxy == proxy) return; // catches repeated nulls
2535            if (proxy != null &&  !proxy.isValid()) {
2536                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2537                return;
2538            }
2539
2540            // This call could be coming from the PacManager, containing the port of the local
2541            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
2542            // global (to get the correct local port), and send a broadcast.
2543            // TODO: Switch PacManager to have its own message to send back rather than
2544            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
2545            if ((mGlobalProxy != null) && (proxy != null) && (proxy.getPacFileUrl() != null)
2546                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2547                mGlobalProxy = proxy;
2548                sendProxyBroadcast(mGlobalProxy);
2549                return;
2550            }
2551            mDefaultProxy = proxy;
2552
2553            if (mGlobalProxy != null) return;
2554            if (!mDefaultProxyDisabled) {
2555                sendProxyBroadcast(proxy);
2556            }
2557        }
2558    }
2559
2560    private void handleDeprecatedGlobalHttpProxy() {
2561        String proxy = Settings.Global.getString(mContext.getContentResolver(),
2562                Settings.Global.HTTP_PROXY);
2563        if (!TextUtils.isEmpty(proxy)) {
2564            String data[] = proxy.split(":");
2565            if (data.length == 0) {
2566                return;
2567            }
2568
2569            String proxyHost =  data[0];
2570            int proxyPort = 8080;
2571            if (data.length > 1) {
2572                try {
2573                    proxyPort = Integer.parseInt(data[1]);
2574                } catch (NumberFormatException e) {
2575                    return;
2576                }
2577            }
2578            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
2579            setGlobalProxy(p);
2580        }
2581    }
2582
2583    private void sendProxyBroadcast(ProxyInfo proxy) {
2584        if (proxy == null) proxy = new ProxyInfo("", 0, "");
2585        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
2586        if (DBG) log("sending Proxy Broadcast for " + proxy);
2587        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2588        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2589            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2590        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2591        final long ident = Binder.clearCallingIdentity();
2592        try {
2593            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2594        } finally {
2595            Binder.restoreCallingIdentity(ident);
2596        }
2597    }
2598
2599    private static class SettingsObserver extends ContentObserver {
2600        private int mWhat;
2601        private Handler mHandler;
2602        SettingsObserver(Handler handler, int what) {
2603            super(handler);
2604            mHandler = handler;
2605            mWhat = what;
2606        }
2607
2608        void observe(Context context) {
2609            ContentResolver resolver = context.getContentResolver();
2610            resolver.registerContentObserver(Settings.Global.getUriFor(
2611                    Settings.Global.HTTP_PROXY), false, this);
2612        }
2613
2614        @Override
2615        public void onChange(boolean selfChange) {
2616            mHandler.obtainMessage(mWhat).sendToTarget();
2617        }
2618    }
2619
2620    private static void log(String s) {
2621        Slog.d(TAG, s);
2622    }
2623
2624    private static void loge(String s) {
2625        Slog.e(TAG, s);
2626    }
2627
2628    int convertFeatureToNetworkType(int networkType, String feature) {
2629        int usedNetworkType = networkType;
2630
2631        if(networkType == ConnectivityManager.TYPE_MOBILE) {
2632            if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2633                usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2634            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2635                usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2636            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2637                    TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2638                usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2639            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2640                usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2641            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2642                usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2643            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2644                usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2645            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2646                usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2647            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_EMERGENCY)) {
2648                usedNetworkType = ConnectivityManager.TYPE_MOBILE_EMERGENCY;
2649            } else {
2650                Slog.e(TAG, "Can't match any mobile netTracker!");
2651            }
2652        } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2653            if (TextUtils.equals(feature, "p2p")) {
2654                usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2655            } else {
2656                Slog.e(TAG, "Can't match any wifi netTracker!");
2657            }
2658        } else {
2659            Slog.e(TAG, "Unexpected network type");
2660        }
2661        return usedNetworkType;
2662    }
2663
2664    private static <T> T checkNotNull(T value, String message) {
2665        if (value == null) {
2666            throw new NullPointerException(message);
2667        }
2668        return value;
2669    }
2670
2671    /**
2672     * Prepare for a VPN application. This method is used by VpnDialogs
2673     * and not available in ConnectivityManager. Permissions are checked
2674     * in Vpn class.
2675     * @hide
2676     */
2677    @Override
2678    public boolean prepareVpn(String oldPackage, String newPackage) {
2679        throwIfLockdownEnabled();
2680        int user = UserHandle.getUserId(Binder.getCallingUid());
2681        synchronized(mVpns) {
2682            return mVpns.get(user).prepare(oldPackage, newPackage);
2683        }
2684    }
2685
2686    /**
2687     * Configure a TUN interface and return its file descriptor. Parameters
2688     * are encoded and opaque to this class. This method is used by VpnBuilder
2689     * and not available in ConnectivityManager. Permissions are checked in
2690     * Vpn class.
2691     * @hide
2692     */
2693    @Override
2694    public ParcelFileDescriptor establishVpn(VpnConfig config) {
2695        throwIfLockdownEnabled();
2696        int user = UserHandle.getUserId(Binder.getCallingUid());
2697        synchronized(mVpns) {
2698            return mVpns.get(user).establish(config);
2699        }
2700    }
2701
2702    /**
2703     * Start legacy VPN, controlling native daemons as needed. Creates a
2704     * secondary thread to perform connection work, returning quickly.
2705     */
2706    @Override
2707    public void startLegacyVpn(VpnProfile profile) {
2708        throwIfLockdownEnabled();
2709        final LinkProperties egress = getActiveLinkProperties();
2710        if (egress == null) {
2711            throw new IllegalStateException("Missing active network connection");
2712        }
2713        int user = UserHandle.getUserId(Binder.getCallingUid());
2714        synchronized(mVpns) {
2715            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
2716        }
2717    }
2718
2719    /**
2720     * Return the information of the ongoing legacy VPN. This method is used
2721     * by VpnSettings and not available in ConnectivityManager. Permissions
2722     * are checked in Vpn class.
2723     * @hide
2724     */
2725    @Override
2726    public LegacyVpnInfo getLegacyVpnInfo() {
2727        throwIfLockdownEnabled();
2728        int user = UserHandle.getUserId(Binder.getCallingUid());
2729        synchronized(mVpns) {
2730            return mVpns.get(user).getLegacyVpnInfo();
2731        }
2732    }
2733
2734    /**
2735     * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
2736     * not available in ConnectivityManager.
2737     * Permissions are checked in Vpn class.
2738     * @hide
2739     */
2740    @Override
2741    public VpnConfig getVpnConfig() {
2742        int user = UserHandle.getUserId(Binder.getCallingUid());
2743        synchronized(mVpns) {
2744            return mVpns.get(user).getVpnConfig();
2745        }
2746    }
2747
2748    @Override
2749    public boolean updateLockdownVpn() {
2750        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
2751            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
2752            return false;
2753        }
2754
2755        // Tear down existing lockdown if profile was removed
2756        mLockdownEnabled = LockdownVpnTracker.isEnabled();
2757        if (mLockdownEnabled) {
2758            if (!mKeyStore.isUnlocked()) {
2759                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
2760                return false;
2761            }
2762
2763            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
2764            final VpnProfile profile = VpnProfile.decode(
2765                    profileName, mKeyStore.get(Credentials.VPN + profileName));
2766            int user = UserHandle.getUserId(Binder.getCallingUid());
2767            synchronized(mVpns) {
2768                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
2769                            profile));
2770            }
2771        } else {
2772            setLockdownTracker(null);
2773        }
2774
2775        return true;
2776    }
2777
2778    /**
2779     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
2780     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
2781     */
2782    private void setLockdownTracker(LockdownVpnTracker tracker) {
2783        // Shutdown any existing tracker
2784        final LockdownVpnTracker existing = mLockdownTracker;
2785        mLockdownTracker = null;
2786        if (existing != null) {
2787            existing.shutdown();
2788        }
2789
2790        try {
2791            if (tracker != null) {
2792                mNetd.setFirewallEnabled(true);
2793                mNetd.setFirewallInterfaceRule("lo", true);
2794                mLockdownTracker = tracker;
2795                mLockdownTracker.init();
2796            } else {
2797                mNetd.setFirewallEnabled(false);
2798            }
2799        } catch (RemoteException e) {
2800            // ignored; NMS lives inside system_server
2801        }
2802    }
2803
2804    private void throwIfLockdownEnabled() {
2805        if (mLockdownEnabled) {
2806            throw new IllegalStateException("Unavailable in lockdown mode");
2807        }
2808    }
2809
2810    public void supplyMessenger(int networkType, Messenger messenger) {
2811        enforceConnectivityInternalPermission();
2812
2813        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
2814            mNetTrackers[networkType].supplyMessenger(messenger);
2815        }
2816    }
2817
2818    public int findConnectionTypeForIface(String iface) {
2819        enforceConnectivityInternalPermission();
2820
2821        if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
2822        for (NetworkStateTracker tracker : mNetTrackers) {
2823            if (tracker != null) {
2824                LinkProperties lp = tracker.getLinkProperties();
2825                if (lp != null && iface.equals(lp.getInterfaceName())) {
2826                    return tracker.getNetworkInfo().getType();
2827                }
2828            }
2829        }
2830        return ConnectivityManager.TYPE_NONE;
2831    }
2832
2833    /**
2834     * Have mobile data fail fast if enabled.
2835     *
2836     * @param enabled DctConstants.ENABLED/DISABLED
2837     */
2838    private void setEnableFailFastMobileData(int enabled) {
2839        int tag;
2840
2841        if (enabled == DctConstants.ENABLED) {
2842            tag = mEnableFailFastMobileDataTag.incrementAndGet();
2843        } else {
2844            tag = mEnableFailFastMobileDataTag.get();
2845        }
2846        mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
2847                         enabled));
2848    }
2849
2850    private boolean isMobileDataStateTrackerReady() {
2851        MobileDataStateTracker mdst =
2852                (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
2853        return (mdst != null) && (mdst.isReady());
2854    }
2855
2856    /**
2857     * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
2858     */
2859
2860    /**
2861     * No connection was possible to the network.
2862     * This is NOT a warm sim.
2863     */
2864    private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
2865
2866    /**
2867     * A connection was made to the internet, all is well.
2868     * This is NOT a warm sim.
2869     */
2870    private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
2871
2872    /**
2873     * A connection was made but no dns server was available to resolve a name to address.
2874     * This is NOT a warm sim since provisioning network is supported.
2875     */
2876    private static final int CMP_RESULT_CODE_NO_DNS = 2;
2877
2878    /**
2879     * A connection was made but could not open a TCP connection.
2880     * This is NOT a warm sim since provisioning network is supported.
2881     */
2882    private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
2883
2884    /**
2885     * A connection was made but there was a redirection, we appear to be in walled garden.
2886     * This is an indication of a warm sim on a mobile network such as T-Mobile.
2887     */
2888    private static final int CMP_RESULT_CODE_REDIRECTED = 4;
2889
2890    /**
2891     * The mobile network is a provisioning network.
2892     * This is an indication of a warm sim on a mobile network such as AT&T.
2893     */
2894    private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
2895
2896    /**
2897     * The mobile network is provisioning
2898     */
2899    private static final int CMP_RESULT_CODE_IS_PROVISIONING = 6;
2900
2901    private AtomicBoolean mIsProvisioningNetwork = new AtomicBoolean(false);
2902    private AtomicBoolean mIsStartingProvisioning = new AtomicBoolean(false);
2903
2904    private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
2905
2906    @Override
2907    public int checkMobileProvisioning(int suggestedTimeOutMs) {
2908        int timeOutMs = -1;
2909        if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
2910        enforceConnectivityInternalPermission();
2911
2912        final long token = Binder.clearCallingIdentity();
2913        try {
2914            timeOutMs = suggestedTimeOutMs;
2915            if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
2916                timeOutMs = CheckMp.MAX_TIMEOUT_MS;
2917            }
2918
2919            // Check that mobile networks are supported
2920            if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
2921                    || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
2922                if (DBG) log("checkMobileProvisioning: X no mobile network");
2923                return timeOutMs;
2924            }
2925
2926            // If we're already checking don't do it again
2927            // TODO: Add a queue of results...
2928            if (mIsCheckingMobileProvisioning.getAndSet(true)) {
2929                if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
2930                return timeOutMs;
2931            }
2932
2933            // Start off with mobile notification off
2934            setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
2935
2936            CheckMp checkMp = new CheckMp(mContext, this);
2937            CheckMp.CallBack cb = new CheckMp.CallBack() {
2938                @Override
2939                void onComplete(Integer result) {
2940                    if (DBG) log("CheckMp.onComplete: result=" + result);
2941                    NetworkInfo ni =
2942                            mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
2943                    switch(result) {
2944                        case CMP_RESULT_CODE_CONNECTABLE:
2945                        case CMP_RESULT_CODE_NO_CONNECTION:
2946                        case CMP_RESULT_CODE_NO_DNS:
2947                        case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
2948                            if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
2949                            break;
2950                        }
2951                        case CMP_RESULT_CODE_REDIRECTED: {
2952                            if (DBG) log("CheckMp.onComplete: warm sim");
2953                            String url = getMobileProvisioningUrl();
2954                            if (TextUtils.isEmpty(url)) {
2955                                url = getMobileRedirectedProvisioningUrl();
2956                            }
2957                            if (TextUtils.isEmpty(url) == false) {
2958                                if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
2959                                setProvNotificationVisible(true,
2960                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
2961                                        url);
2962                            } else {
2963                                if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
2964                            }
2965                            break;
2966                        }
2967                        case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
2968                            String url = getMobileProvisioningUrl();
2969                            if (TextUtils.isEmpty(url) == false) {
2970                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
2971                                setProvNotificationVisible(true,
2972                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
2973                                        url);
2974                                // Mark that we've got a provisioning network and
2975                                // Disable Mobile Data until user actually starts provisioning.
2976                                mIsProvisioningNetwork.set(true);
2977                                MobileDataStateTracker mdst = (MobileDataStateTracker)
2978                                        mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2979
2980                                // Disable radio until user starts provisioning
2981                                mdst.setRadio(false);
2982                            } else {
2983                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
2984                            }
2985                            break;
2986                        }
2987                        case CMP_RESULT_CODE_IS_PROVISIONING: {
2988                            // FIXME: Need to know when provisioning is done. Probably we can
2989                            // check the completion status if successful we're done if we
2990                            // "timedout" or still connected to provisioning APN turn off data?
2991                            if (DBG) log("CheckMp.onComplete: provisioning started");
2992                            mIsStartingProvisioning.set(false);
2993                            break;
2994                        }
2995                        default: {
2996                            loge("CheckMp.onComplete: ignore unexpected result=" + result);
2997                            break;
2998                        }
2999                    }
3000                    mIsCheckingMobileProvisioning.set(false);
3001                }
3002            };
3003            CheckMp.Params params =
3004                    new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3005            if (DBG) log("checkMobileProvisioning: params=" + params);
3006            // TODO: Reenable when calls to the now defunct
3007            //       MobileDataStateTracker.isProvisioningNetwork() are removed.
3008            //       This code should be moved to the Telephony code.
3009            // checkMp.execute(params);
3010        } finally {
3011            Binder.restoreCallingIdentity(token);
3012            if (DBG) log("checkMobileProvisioning: X");
3013        }
3014        return timeOutMs;
3015    }
3016
3017    static class CheckMp extends
3018            AsyncTask<CheckMp.Params, Void, Integer> {
3019        private static final String CHECKMP_TAG = "CheckMp";
3020
3021        // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
3022        private static boolean mTestingFailures;
3023
3024        // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
3025        private static final int MAX_LOOPS = 4;
3026
3027        // Number of milli-seconds to complete all of the retires
3028        public static final int MAX_TIMEOUT_MS =  60000;
3029
3030        // The socket should retry only 5 seconds, the default is longer
3031        private static final int SOCKET_TIMEOUT_MS = 5000;
3032
3033        // Sleep time for network errors
3034        private static final int NET_ERROR_SLEEP_SEC = 3;
3035
3036        // Sleep time for network route establishment
3037        private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
3038
3039        // Short sleep time for polling :(
3040        private static final int POLLING_SLEEP_SEC = 1;
3041
3042        private Context mContext;
3043        private ConnectivityService mCs;
3044        private TelephonyManager mTm;
3045        private Params mParams;
3046
3047        /**
3048         * Parameters for AsyncTask.execute
3049         */
3050        static class Params {
3051            private String mUrl;
3052            private long mTimeOutMs;
3053            private CallBack mCb;
3054
3055            Params(String url, long timeOutMs, CallBack cb) {
3056                mUrl = url;
3057                mTimeOutMs = timeOutMs;
3058                mCb = cb;
3059            }
3060
3061            @Override
3062            public String toString() {
3063                return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3064            }
3065        }
3066
3067        // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
3068        // issued by name or ip address, for Google its by name so when we construct
3069        // this HostnameVerifier we'll pass the original Uri and use it to verify
3070        // the host. If the host name in the original uril fails we'll test the
3071        // hostname parameter just incase things change.
3072        static class CheckMpHostnameVerifier implements HostnameVerifier {
3073            Uri mOrgUri;
3074
3075            CheckMpHostnameVerifier(Uri orgUri) {
3076                mOrgUri = orgUri;
3077            }
3078
3079            @Override
3080            public boolean verify(String hostname, SSLSession session) {
3081                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
3082                String orgUriHost = mOrgUri.getHost();
3083                boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
3084                if (DBG) {
3085                    log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
3086                        + " orgUriHost=" + orgUriHost);
3087                }
3088                return retVal;
3089            }
3090        }
3091
3092        /**
3093         * The call back object passed in Params. onComplete will be called
3094         * on the main thread.
3095         */
3096        abstract static class CallBack {
3097            // Called on the main thread.
3098            abstract void onComplete(Integer result);
3099        }
3100
3101        public CheckMp(Context context, ConnectivityService cs) {
3102            if (Build.IS_DEBUGGABLE) {
3103                mTestingFailures =
3104                        SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
3105            } else {
3106                mTestingFailures = false;
3107            }
3108
3109            mContext = context;
3110            mCs = cs;
3111
3112            // Setup access to TelephonyService we'll be using.
3113            mTm = (TelephonyManager) mContext.getSystemService(
3114                    Context.TELEPHONY_SERVICE);
3115        }
3116
3117        /**
3118         * Get the default url to use for the test.
3119         */
3120        public String getDefaultUrl() {
3121            // See http://go/clientsdns for usage approval
3122            String server = Settings.Global.getString(mContext.getContentResolver(),
3123                    Settings.Global.CAPTIVE_PORTAL_SERVER);
3124            if (server == null) {
3125                server = "clients3.google.com";
3126            }
3127            return "http://" + server + "/generate_204";
3128        }
3129
3130        /**
3131         * Detect if its possible to connect to the http url. DNS based detection techniques
3132         * do not work at all hotspots. The best way to check is to perform a request to
3133         * a known address that fetches the data we expect.
3134         */
3135        private synchronized Integer isMobileOk(Params params) {
3136            Integer result = CMP_RESULT_CODE_NO_CONNECTION;
3137            Uri orgUri = Uri.parse(params.mUrl);
3138            Random rand = new Random();
3139            mParams = params;
3140
3141            if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3142                result = CMP_RESULT_CODE_NO_CONNECTION;
3143                log("isMobileOk: X not mobile capable result=" + result);
3144                return result;
3145            }
3146
3147            if (mCs.mIsStartingProvisioning.get()) {
3148                result = CMP_RESULT_CODE_IS_PROVISIONING;
3149                log("isMobileOk: X is provisioning result=" + result);
3150                return result;
3151            }
3152
3153            // See if we've already determined we've got a provisioning connection,
3154            // if so we don't need to do anything active.
3155            MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
3156                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3157            boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
3158            log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
3159
3160            MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
3161                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
3162            boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
3163            log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
3164
3165            if (isDefaultProvisioning || isHipriProvisioning) {
3166                result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
3167                log("isMobileOk: X default || hipri is provisioning result=" + result);
3168                return result;
3169            }
3170
3171            try {
3172                // Continue trying to connect until time has run out
3173                long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3174
3175                if (!mCs.isMobileDataStateTrackerReady()) {
3176                    // Wait for MobileDataStateTracker to be ready.
3177                    if (DBG) log("isMobileOk: mdst is not ready");
3178                    while(SystemClock.elapsedRealtime() < endTime) {
3179                        if (mCs.isMobileDataStateTrackerReady()) {
3180                            // Enable fail fast as we'll do retries here and use a
3181                            // hipri connection so the default connection stays active.
3182                            if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
3183                            mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3184                            break;
3185                        }
3186                        sleep(POLLING_SLEEP_SEC);
3187                    }
3188                }
3189
3190                log("isMobileOk: start hipri url=" + params.mUrl);
3191
3192                // First wait until we can start using hipri
3193                Binder binder = new Binder();
3194/*
3195                while(SystemClock.elapsedRealtime() < endTime) {
3196                    int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3197                            Phone.FEATURE_ENABLE_HIPRI, binder);
3198                    if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
3199                        || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
3200                            log("isMobileOk: hipri started");
3201                            break;
3202                    }
3203                    if (VDBG) log("isMobileOk: hipri not started yet");
3204                    result = CMP_RESULT_CODE_NO_CONNECTION;
3205                    sleep(POLLING_SLEEP_SEC);
3206                }
3207*/
3208                // Continue trying to connect until time has run out
3209                while(SystemClock.elapsedRealtime() < endTime) {
3210                    try {
3211                        // Wait for hipri to connect.
3212                        // TODO: Don't poll and handle situation where hipri fails
3213                        // because default is retrying. See b/9569540
3214                        NetworkInfo.State state = mCs
3215                                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3216                        if (state != NetworkInfo.State.CONNECTED) {
3217                            if (true/*VDBG*/) {
3218                                log("isMobileOk: not connected ni=" +
3219                                    mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3220                            }
3221                            sleep(POLLING_SLEEP_SEC);
3222                            result = CMP_RESULT_CODE_NO_CONNECTION;
3223                            continue;
3224                        }
3225
3226                        // Hipri has started check if this is a provisioning url
3227                        MobileDataStateTracker mdst = (MobileDataStateTracker)
3228                                mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
3229                        if (mdst.isProvisioningNetwork()) {
3230                            result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
3231                            if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
3232                            return result;
3233                        } else {
3234                            if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
3235                        }
3236
3237                        // Get of the addresses associated with the url host. We need to use the
3238                        // address otherwise HttpURLConnection object will use the name to get
3239                        // the addresses and will try every address but that will bypass the
3240                        // route to host we setup and the connection could succeed as the default
3241                        // interface might be connected to the internet via wifi or other interface.
3242                        InetAddress[] addresses;
3243                        try {
3244                            addresses = InetAddress.getAllByName(orgUri.getHost());
3245                        } catch (UnknownHostException e) {
3246                            result = CMP_RESULT_CODE_NO_DNS;
3247                            log("isMobileOk: X UnknownHostException result=" + result);
3248                            return result;
3249                        }
3250                        log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3251
3252                        // Get the type of addresses supported by this link
3253                        LinkProperties lp = mCs.getLinkPropertiesForTypeInternal(
3254                                ConnectivityManager.TYPE_MOBILE_HIPRI);
3255                        boolean linkHasIpv4 = lp.hasIPv4Address();
3256                        boolean linkHasIpv6 = lp.hasGlobalIPv6Address();
3257                        log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3258                                + " linkHasIpv6=" + linkHasIpv6);
3259
3260                        final ArrayList<InetAddress> validAddresses =
3261                                new ArrayList<InetAddress>(addresses.length);
3262
3263                        for (InetAddress addr : addresses) {
3264                            if (((addr instanceof Inet4Address) && linkHasIpv4) ||
3265                                    ((addr instanceof Inet6Address) && linkHasIpv6)) {
3266                                validAddresses.add(addr);
3267                            }
3268                        }
3269
3270                        if (validAddresses.size() == 0) {
3271                            return CMP_RESULT_CODE_NO_CONNECTION;
3272                        }
3273
3274                        int addrTried = 0;
3275                        while (true) {
3276                            // Loop through at most MAX_LOOPS valid addresses or until
3277                            // we run out of time
3278                            if (addrTried++ >= MAX_LOOPS) {
3279                                log("isMobileOk: too many loops tried - giving up");
3280                                break;
3281                            }
3282                            if (SystemClock.elapsedRealtime() >= endTime) {
3283                                log("isMobileOk: spend too much time - giving up");
3284                                break;
3285                            }
3286
3287                            InetAddress hostAddr = validAddresses.get(rand.nextInt(
3288                                    validAddresses.size()));
3289
3290                            // Make a route to host so we check the specific interface.
3291                            if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3292                                    hostAddr.getAddress())) {
3293                                // Wait a short time to be sure the route is established ??
3294                                log("isMobileOk:"
3295                                        + " wait to establish route to hostAddr=" + hostAddr);
3296                                sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
3297                            } else {
3298                                log("isMobileOk:"
3299                                        + " could not establish route to hostAddr=" + hostAddr);
3300                                // Wait a short time before the next attempt
3301                                sleep(NET_ERROR_SLEEP_SEC);
3302                                continue;
3303                            }
3304
3305                            // Rewrite the url to have numeric address to use the specific route
3306                            // using http for half the attempts and https for the other half.
3307                            // Doing https first and http second as on a redirected walled garden
3308                            // such as t-mobile uses we get a SocketTimeoutException: "SSL
3309                            // handshake timed out" which we declare as
3310                            // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
3311                            // having http second we will be using logic used for some time.
3312                            URL newUrl;
3313                            String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
3314                            newUrl = new URL(scheme, hostAddr.getHostAddress(),
3315                                        orgUri.getPath());
3316                            log("isMobileOk: newUrl=" + newUrl);
3317
3318                            HttpURLConnection urlConn = null;
3319                            try {
3320                                // Open the connection set the request headers and get the response
3321                                urlConn = (HttpURLConnection)newUrl.openConnection(
3322                                        java.net.Proxy.NO_PROXY);
3323                                if (scheme.equals("https")) {
3324                                    ((HttpsURLConnection)urlConn).setHostnameVerifier(
3325                                            new CheckMpHostnameVerifier(orgUri));
3326                                }
3327                                urlConn.setInstanceFollowRedirects(false);
3328                                urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3329                                urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3330                                urlConn.setUseCaches(false);
3331                                urlConn.setAllowUserInteraction(false);
3332                                // Set the "Connection" to "Close" as by default "Keep-Alive"
3333                                // is used which is useless in this case.
3334                                urlConn.setRequestProperty("Connection", "close");
3335                                int responseCode = urlConn.getResponseCode();
3336
3337                                // For debug display the headers
3338                                Map<String, List<String>> headers = urlConn.getHeaderFields();
3339                                log("isMobileOk: headers=" + headers);
3340
3341                                // Close the connection
3342                                urlConn.disconnect();
3343                                urlConn = null;
3344
3345                                if (mTestingFailures) {
3346                                    // Pretend no connection, this tests using http and https
3347                                    result = CMP_RESULT_CODE_NO_CONNECTION;
3348                                    log("isMobileOk: TESTING_FAILURES, pretend no connction");
3349                                    continue;
3350                                }
3351
3352                                if (responseCode == 204) {
3353                                    // Return
3354                                    result = CMP_RESULT_CODE_CONNECTABLE;
3355                                    log("isMobileOk: X got expected responseCode=" + responseCode
3356                                            + " result=" + result);
3357                                    return result;
3358                                } else {
3359                                    // Retry to be sure this was redirected, we've gotten
3360                                    // occasions where a server returned 200 even though
3361                                    // the device didn't have a "warm" sim.
3362                                    log("isMobileOk: not expected responseCode=" + responseCode);
3363                                    // TODO - it would be nice in the single-address case to do
3364                                    // another DNS resolve here, but flushing the cache is a bit
3365                                    // heavy-handed.
3366                                    result = CMP_RESULT_CODE_REDIRECTED;
3367                                }
3368                            } catch (Exception e) {
3369                                log("isMobileOk: HttpURLConnection Exception" + e);
3370                                result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
3371                                if (urlConn != null) {
3372                                    urlConn.disconnect();
3373                                    urlConn = null;
3374                                }
3375                                sleep(NET_ERROR_SLEEP_SEC);
3376                                continue;
3377                            }
3378                        }
3379                        log("isMobileOk: X loops|timed out result=" + result);
3380                        return result;
3381                    } catch (Exception e) {
3382                        log("isMobileOk: Exception e=" + e);
3383                        continue;
3384                    }
3385                }
3386                log("isMobileOk: timed out");
3387            } finally {
3388                log("isMobileOk: F stop hipri");
3389                mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3390//                mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3391//                        Phone.FEATURE_ENABLE_HIPRI);
3392
3393                // Wait for hipri to disconnect.
3394                long endTime = SystemClock.elapsedRealtime() + 5000;
3395
3396                while(SystemClock.elapsedRealtime() < endTime) {
3397                    NetworkInfo.State state = mCs
3398                            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3399                    if (state != NetworkInfo.State.DISCONNECTED) {
3400                        if (VDBG) {
3401                            log("isMobileOk: connected ni=" +
3402                                mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3403                        }
3404                        sleep(POLLING_SLEEP_SEC);
3405                        continue;
3406                    }
3407                }
3408
3409                log("isMobileOk: X result=" + result);
3410            }
3411            return result;
3412        }
3413
3414        @Override
3415        protected Integer doInBackground(Params... params) {
3416            return isMobileOk(params[0]);
3417        }
3418
3419        @Override
3420        protected void onPostExecute(Integer result) {
3421            log("onPostExecute: result=" + result);
3422            if ((mParams != null) && (mParams.mCb != null)) {
3423                mParams.mCb.onComplete(result);
3424            }
3425        }
3426
3427        private String inetAddressesToString(InetAddress[] addresses) {
3428            StringBuffer sb = new StringBuffer();
3429            boolean firstTime = true;
3430            for(InetAddress addr : addresses) {
3431                if (firstTime) {
3432                    firstTime = false;
3433                } else {
3434                    sb.append(",");
3435                }
3436                sb.append(addr);
3437            }
3438            return sb.toString();
3439        }
3440
3441        private void printNetworkInfo() {
3442            boolean hasIccCard = mTm.hasIccCard();
3443            int simState = mTm.getSimState();
3444            log("hasIccCard=" + hasIccCard
3445                    + " simState=" + simState);
3446            NetworkInfo[] ni = mCs.getAllNetworkInfo();
3447            if (ni != null) {
3448                log("ni.length=" + ni.length);
3449                for (NetworkInfo netInfo: ni) {
3450                    log("netInfo=" + netInfo.toString());
3451                }
3452            } else {
3453                log("no network info ni=null");
3454            }
3455        }
3456
3457        /**
3458         * Sleep for a few seconds then return.
3459         * @param seconds
3460         */
3461        private static void sleep(int seconds) {
3462            long stopTime = System.nanoTime() + (seconds * 1000000000);
3463            long sleepTime;
3464            while ((sleepTime = stopTime - System.nanoTime()) > 0) {
3465                try {
3466                    Thread.sleep(sleepTime / 1000000);
3467                } catch (InterruptedException ignored) {
3468                }
3469            }
3470        }
3471
3472        private static void log(String s) {
3473            Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
3474        }
3475    }
3476
3477    // TODO: Move to ConnectivityManager and make public?
3478    private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
3479            "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
3480
3481    private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
3482        @Override
3483        public void onReceive(Context context, Intent intent) {
3484            if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
3485                handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
3486            }
3487        }
3488    };
3489
3490    private void handleMobileProvisioningAction(String url) {
3491        // Mark notification as not visible
3492        setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
3493
3494        // Check airplane mode
3495        boolean isAirplaneModeOn = Settings.System.getInt(mContext.getContentResolver(),
3496                Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
3497        // If provisioning network and not in airplane mode handle as a special case,
3498        // otherwise launch browser with the intent directly.
3499        if (mIsProvisioningNetwork.get() && !isAirplaneModeOn) {
3500            if (DBG) log("handleMobileProvisioningAction: on prov network enable then launch");
3501            mIsProvisioningNetwork.set(false);
3502//            mIsStartingProvisioning.set(true);
3503//            MobileDataStateTracker mdst = (MobileDataStateTracker)
3504//                    mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3505            // Radio was disabled on CMP_RESULT_CODE_PROVISIONING_NETWORK, enable it here
3506//            mdst.setRadio(true);
3507//            mdst.setEnableFailFastMobileData(DctConstants.ENABLED);
3508//            mdst.enableMobileProvisioning(url);
3509        } else {
3510            if (DBG) log("handleMobileProvisioningAction: not prov network");
3511            mIsProvisioningNetwork.set(false);
3512            // Check for  apps that can handle provisioning first
3513            Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP);
3514            provisioningIntent.addCategory(TelephonyIntents.CATEGORY_MCCMNC_PREFIX
3515                    + mTelephonyManager.getSimOperator());
3516            if (mContext.getPackageManager().resolveActivity(provisioningIntent, 0 /* flags */)
3517                    != null) {
3518                provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3519                        Intent.FLAG_ACTIVITY_NEW_TASK);
3520                mContext.startActivity(provisioningIntent);
3521            } else {
3522                // If no apps exist, use standard URL ACTION_VIEW method
3523                Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
3524                        Intent.CATEGORY_APP_BROWSER);
3525                newIntent.setData(Uri.parse(url));
3526                newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3527                        Intent.FLAG_ACTIVITY_NEW_TASK);
3528                try {
3529                    mContext.startActivity(newIntent);
3530                } catch (ActivityNotFoundException e) {
3531                    loge("handleMobileProvisioningAction: startActivity failed" + e);
3532                }
3533            }
3534        }
3535    }
3536
3537    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3538    private volatile boolean mIsNotificationVisible = false;
3539
3540    private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
3541            String url) {
3542        if (DBG) {
3543            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
3544                + " extraInfo=" + extraInfo + " url=" + url);
3545        }
3546        Intent intent = null;
3547        PendingIntent pendingIntent = null;
3548        if (visible) {
3549            switch (networkType) {
3550                case ConnectivityManager.TYPE_WIFI:
3551                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
3552                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3553                            Intent.FLAG_ACTIVITY_NEW_TASK);
3554                    pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
3555                    break;
3556                case ConnectivityManager.TYPE_MOBILE:
3557                case ConnectivityManager.TYPE_MOBILE_HIPRI:
3558                    intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
3559                    intent.putExtra("EXTRA_URL", url);
3560                    intent.setFlags(0);
3561                    pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
3562                    break;
3563                default:
3564                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
3565                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3566                            Intent.FLAG_ACTIVITY_NEW_TASK);
3567                    pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
3568                    break;
3569            }
3570        }
3571        // Concatenate the range of types onto the range of NetIDs.
3572        int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3573        setProvNotificationVisibleIntent(visible, id, networkType, extraInfo, pendingIntent);
3574    }
3575
3576    /**
3577     * Show or hide network provisioning notificaitons.
3578     *
3579     * @param id an identifier that uniquely identifies this notification.  This must match
3580     *         between show and hide calls.  We use the NetID value but for legacy callers
3581     *         we concatenate the range of types with the range of NetIDs.
3582     */
3583    private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
3584            String extraInfo, PendingIntent intent) {
3585        if (DBG) {
3586            log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3587                networkType + " extraInfo=" + extraInfo);
3588        }
3589
3590        Resources r = Resources.getSystem();
3591        NotificationManager notificationManager = (NotificationManager) mContext
3592            .getSystemService(Context.NOTIFICATION_SERVICE);
3593
3594        if (visible) {
3595            CharSequence title;
3596            CharSequence details;
3597            int icon;
3598            Notification notification = new Notification();
3599            switch (networkType) {
3600                case ConnectivityManager.TYPE_WIFI:
3601                    title = r.getString(R.string.wifi_available_sign_in, 0);
3602                    details = r.getString(R.string.network_available_sign_in_detailed,
3603                            extraInfo);
3604                    icon = R.drawable.stat_notify_wifi_in_range;
3605                    break;
3606                case ConnectivityManager.TYPE_MOBILE:
3607                case ConnectivityManager.TYPE_MOBILE_HIPRI:
3608                    title = r.getString(R.string.network_available_sign_in, 0);
3609                    // TODO: Change this to pull from NetworkInfo once a printable
3610                    // name has been added to it
3611                    details = mTelephonyManager.getNetworkOperatorName();
3612                    icon = R.drawable.stat_notify_rssi_in_range;
3613                    break;
3614                default:
3615                    title = r.getString(R.string.network_available_sign_in, 0);
3616                    details = r.getString(R.string.network_available_sign_in_detailed,
3617                            extraInfo);
3618                    icon = R.drawable.stat_notify_rssi_in_range;
3619                    break;
3620            }
3621
3622            notification.when = 0;
3623            notification.icon = icon;
3624            notification.flags = Notification.FLAG_AUTO_CANCEL;
3625            notification.tickerText = title;
3626            notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
3627            notification.contentIntent = intent;
3628
3629            try {
3630                notificationManager.notify(NOTIFICATION_ID, id, notification);
3631            } catch (NullPointerException npe) {
3632                loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3633                npe.printStackTrace();
3634            }
3635        } else {
3636            try {
3637                notificationManager.cancel(NOTIFICATION_ID, id);
3638            } catch (NullPointerException npe) {
3639                loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3640                npe.printStackTrace();
3641            }
3642        }
3643        mIsNotificationVisible = visible;
3644    }
3645
3646    /** Location to an updatable file listing carrier provisioning urls.
3647     *  An example:
3648     *
3649     * <?xml version="1.0" encoding="utf-8"?>
3650     *  <provisioningUrls>
3651     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
3652     *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3653     *  </provisioningUrls>
3654     */
3655    private static final String PROVISIONING_URL_PATH =
3656            "/data/misc/radio/provisioning_urls.xml";
3657    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3658
3659    /** XML tag for root element. */
3660    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3661    /** XML tag for individual url */
3662    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3663    /** XML tag for redirected url */
3664    private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3665    /** XML attribute for mcc */
3666    private static final String ATTR_MCC = "mcc";
3667    /** XML attribute for mnc */
3668    private static final String ATTR_MNC = "mnc";
3669
3670    private static final int REDIRECTED_PROVISIONING = 1;
3671    private static final int PROVISIONING = 2;
3672
3673    private String getProvisioningUrlBaseFromFile(int type) {
3674        FileReader fileReader = null;
3675        XmlPullParser parser = null;
3676        Configuration config = mContext.getResources().getConfiguration();
3677        String tagType;
3678
3679        switch (type) {
3680            case PROVISIONING:
3681                tagType = TAG_PROVISIONING_URL;
3682                break;
3683            case REDIRECTED_PROVISIONING:
3684                tagType = TAG_REDIRECTED_URL;
3685                break;
3686            default:
3687                throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3688                        type);
3689        }
3690
3691        try {
3692            fileReader = new FileReader(mProvisioningUrlFile);
3693            parser = Xml.newPullParser();
3694            parser.setInput(fileReader);
3695            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3696
3697            while (true) {
3698                XmlUtils.nextElement(parser);
3699
3700                String element = parser.getName();
3701                if (element == null) break;
3702
3703                if (element.equals(tagType)) {
3704                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
3705                    try {
3706                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3707                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
3708                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3709                                parser.next();
3710                                if (parser.getEventType() == XmlPullParser.TEXT) {
3711                                    return parser.getText();
3712                                }
3713                            }
3714                        }
3715                    } catch (NumberFormatException e) {
3716                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3717                    }
3718                }
3719            }
3720            return null;
3721        } catch (FileNotFoundException e) {
3722            loge("Carrier Provisioning Urls file not found");
3723        } catch (XmlPullParserException e) {
3724            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3725        } catch (IOException e) {
3726            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3727        } finally {
3728            if (fileReader != null) {
3729                try {
3730                    fileReader.close();
3731                } catch (IOException e) {}
3732            }
3733        }
3734        return null;
3735    }
3736
3737    @Override
3738    public String getMobileRedirectedProvisioningUrl() {
3739        enforceConnectivityInternalPermission();
3740        String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3741        if (TextUtils.isEmpty(url)) {
3742            url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3743        }
3744        return url;
3745    }
3746
3747    @Override
3748    public String getMobileProvisioningUrl() {
3749        enforceConnectivityInternalPermission();
3750        String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3751        if (TextUtils.isEmpty(url)) {
3752            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3753            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
3754        } else {
3755            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
3756        }
3757        // populate the iccid, imei and phone number in the provisioning url.
3758        if (!TextUtils.isEmpty(url)) {
3759            String phoneNumber = mTelephonyManager.getLine1Number();
3760            if (TextUtils.isEmpty(phoneNumber)) {
3761                phoneNumber = "0000000000";
3762            }
3763            url = String.format(url,
3764                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
3765                    mTelephonyManager.getDeviceId() /* IMEI */,
3766                    phoneNumber /* Phone numer */);
3767        }
3768
3769        return url;
3770    }
3771
3772    @Override
3773    public void setProvisioningNotificationVisible(boolean visible, int networkType,
3774            String extraInfo, String url) {
3775        enforceConnectivityInternalPermission();
3776        setProvNotificationVisible(visible, networkType, extraInfo, url);
3777    }
3778
3779    @Override
3780    public void setAirplaneMode(boolean enable) {
3781        enforceConnectivityInternalPermission();
3782        final long ident = Binder.clearCallingIdentity();
3783        try {
3784            final ContentResolver cr = mContext.getContentResolver();
3785            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3786            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3787            intent.putExtra("state", enable);
3788            mContext.sendBroadcast(intent);
3789        } finally {
3790            Binder.restoreCallingIdentity(ident);
3791        }
3792    }
3793
3794    private void onUserStart(int userId) {
3795        synchronized(mVpns) {
3796            Vpn userVpn = mVpns.get(userId);
3797            if (userVpn != null) {
3798                loge("Starting user already has a VPN");
3799                return;
3800            }
3801            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, this, userId);
3802            mVpns.put(userId, userVpn);
3803        }
3804    }
3805
3806    private void onUserStop(int userId) {
3807        synchronized(mVpns) {
3808            Vpn userVpn = mVpns.get(userId);
3809            if (userVpn == null) {
3810                loge("Stopping user has no VPN");
3811                return;
3812            }
3813            mVpns.delete(userId);
3814        }
3815    }
3816
3817    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3818        @Override
3819        public void onReceive(Context context, Intent intent) {
3820            final String action = intent.getAction();
3821            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3822            if (userId == UserHandle.USER_NULL) return;
3823
3824            if (Intent.ACTION_USER_STARTING.equals(action)) {
3825                onUserStart(userId);
3826            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3827                onUserStop(userId);
3828            }
3829        }
3830    };
3831
3832    @Override
3833    public LinkQualityInfo getLinkQualityInfo(int networkType) {
3834        enforceAccessPermission();
3835        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3836            return mNetTrackers[networkType].getLinkQualityInfo();
3837        } else {
3838            return null;
3839        }
3840    }
3841
3842    @Override
3843    public LinkQualityInfo getActiveLinkQualityInfo() {
3844        enforceAccessPermission();
3845        if (isNetworkTypeValid(mActiveDefaultNetwork) &&
3846                mNetTrackers[mActiveDefaultNetwork] != null) {
3847            return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
3848        } else {
3849            return null;
3850        }
3851    }
3852
3853    @Override
3854    public LinkQualityInfo[] getAllLinkQualityInfo() {
3855        enforceAccessPermission();
3856        final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
3857        for (NetworkStateTracker tracker : mNetTrackers) {
3858            if (tracker != null) {
3859                LinkQualityInfo li = tracker.getLinkQualityInfo();
3860                if (li != null) {
3861                    result.add(li);
3862                }
3863            }
3864        }
3865
3866        return result.toArray(new LinkQualityInfo[result.size()]);
3867    }
3868
3869    /* Infrastructure for network sampling */
3870
3871    private void handleNetworkSamplingTimeout() {
3872
3873        log("Sampling interval elapsed, updating statistics ..");
3874
3875        // initialize list of interfaces ..
3876        Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
3877                new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
3878        for (NetworkStateTracker tracker : mNetTrackers) {
3879            if (tracker != null) {
3880                String ifaceName = tracker.getNetworkInterfaceName();
3881                if (ifaceName != null) {
3882                    mapIfaceToSample.put(ifaceName, null);
3883                }
3884            }
3885        }
3886
3887        // Read samples for all interfaces
3888        SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
3889
3890        // process samples for all networks
3891        for (NetworkStateTracker tracker : mNetTrackers) {
3892            if (tracker != null) {
3893                String ifaceName = tracker.getNetworkInterfaceName();
3894                SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
3895                if (ss != null) {
3896                    // end the previous sampling cycle
3897                    tracker.stopSampling(ss);
3898                    // start a new sampling cycle ..
3899                    tracker.startSampling(ss);
3900                }
3901            }
3902        }
3903
3904        log("Done.");
3905
3906        int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
3907                Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
3908                DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
3909
3910        if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
3911
3912        setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
3913    }
3914
3915    /**
3916     * Sets a network sampling alarm.
3917     */
3918    void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
3919        long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
3920        int alarmType;
3921        if (Resources.getSystem().getBoolean(
3922                R.bool.config_networkSamplingWakesDevice)) {
3923            alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
3924        } else {
3925            alarmType = AlarmManager.ELAPSED_REALTIME;
3926        }
3927        mAlarmManager.set(alarmType, wakeupTime, intent);
3928    }
3929
3930    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3931            new HashMap<Messenger, NetworkFactoryInfo>();
3932    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3933            new HashMap<NetworkRequest, NetworkRequestInfo>();
3934
3935    private static class NetworkFactoryInfo {
3936        public final String name;
3937        public final Messenger messenger;
3938        public final AsyncChannel asyncChannel;
3939
3940        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3941            this.name = name;
3942            this.messenger = messenger;
3943            this.asyncChannel = asyncChannel;
3944        }
3945    }
3946
3947    /**
3948     * Tracks info about the requester.
3949     * Also used to notice when the calling process dies so we can self-expire
3950     */
3951    private class NetworkRequestInfo implements IBinder.DeathRecipient {
3952        static final boolean REQUEST = true;
3953        static final boolean LISTEN = false;
3954
3955        final NetworkRequest request;
3956        IBinder mBinder;
3957        final int mPid;
3958        final int mUid;
3959        final Messenger messenger;
3960        final boolean isRequest;
3961
3962        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3963            super();
3964            messenger = m;
3965            request = r;
3966            mBinder = binder;
3967            mPid = getCallingPid();
3968            mUid = getCallingUid();
3969            this.isRequest = isRequest;
3970
3971            try {
3972                mBinder.linkToDeath(this, 0);
3973            } catch (RemoteException e) {
3974                binderDied();
3975            }
3976        }
3977
3978        void unlinkDeathRecipient() {
3979            mBinder.unlinkToDeath(this, 0);
3980        }
3981
3982        public void binderDied() {
3983            log("ConnectivityService NetworkRequestInfo binderDied(" +
3984                    request + ", " + mBinder + ")");
3985            releaseNetworkRequest(request);
3986        }
3987
3988        public String toString() {
3989            return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
3990                    mPid + " for " + request;
3991        }
3992    }
3993
3994    @Override
3995    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
3996            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
3997        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
3998                == false) {
3999            enforceConnectivityInternalPermission();
4000        } else {
4001            enforceChangePermission();
4002        }
4003
4004        networkCapabilities = new NetworkCapabilities(networkCapabilities);
4005
4006        // if UID is restricted, don't allow them to bring up metered APNs
4007        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
4008                == false) {
4009            final int uidRules;
4010            synchronized(mRulesLock) {
4011                uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
4012            }
4013            if ((uidRules & RULE_REJECT_METERED) != 0) {
4014                // we could silently fail or we can filter the available nets to only give
4015                // them those they have access to.  Chose the more useful
4016                networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
4017            }
4018        }
4019
4020        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
4021            throw new IllegalArgumentException("Bad timeout specified");
4022        }
4023        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
4024                nextNetworkRequestId());
4025        if (DBG) log("requestNetwork for " + networkRequest);
4026        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
4027                NetworkRequestInfo.REQUEST);
4028
4029        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
4030        if (timeoutMs > 0) {
4031            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
4032                    nri), timeoutMs);
4033        }
4034        return networkRequest;
4035    }
4036
4037    @Override
4038    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4039            PendingIntent operation) {
4040        // TODO
4041        return null;
4042    }
4043
4044    @Override
4045    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4046            Messenger messenger, IBinder binder) {
4047        enforceAccessPermission();
4048
4049        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
4050                networkCapabilities), TYPE_NONE, nextNetworkRequestId());
4051        if (DBG) log("listenForNetwork for " + networkRequest);
4052        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
4053                NetworkRequestInfo.LISTEN);
4054
4055        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4056        return networkRequest;
4057    }
4058
4059    @Override
4060    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4061            PendingIntent operation) {
4062    }
4063
4064    @Override
4065    public void releaseNetworkRequest(NetworkRequest networkRequest) {
4066        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4067                0, networkRequest));
4068    }
4069
4070    @Override
4071    public void registerNetworkFactory(Messenger messenger, String name) {
4072        enforceConnectivityInternalPermission();
4073        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4074        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
4075    }
4076
4077    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
4078        if (VDBG) log("Got NetworkFactory Messenger for " + nfi.name);
4079        mNetworkFactoryInfos.put(nfi.messenger, nfi);
4080        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4081    }
4082
4083    @Override
4084    public void unregisterNetworkFactory(Messenger messenger) {
4085        enforceConnectivityInternalPermission();
4086        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4087    }
4088
4089    private void handleUnregisterNetworkFactory(Messenger messenger) {
4090        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4091        if (nfi == null) {
4092            if (VDBG) log("Failed to find Messenger in unregisterNetworkFactory");
4093            return;
4094        }
4095        if (VDBG) log("unregisterNetworkFactory for " + nfi.name);
4096    }
4097
4098    /**
4099     * NetworkAgentInfo supporting a request by requestId.
4100     * These have already been vetted (their Capabilities satisfy the request)
4101     * and the are the highest scored network available.
4102     * the are keyed off the Requests requestId.
4103     */
4104    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4105            new SparseArray<NetworkAgentInfo>();
4106
4107    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4108            new SparseArray<NetworkAgentInfo>();
4109
4110    // NetworkAgentInfo keyed off its connecting messenger
4111    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
4112    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4113            new HashMap<Messenger, NetworkAgentInfo>();
4114
4115    private final NetworkRequest mDefaultRequest;
4116
4117    private boolean isDefaultNetwork(NetworkAgentInfo nai) {
4118        return mNetworkForRequestId.get(mDefaultRequest.requestId) == nai;
4119    }
4120
4121    public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
4122            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
4123            int currentScore, NetworkMisc networkMisc) {
4124        enforceConnectivityInternalPermission();
4125
4126        NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), nextNetId(),
4127            new NetworkInfo(networkInfo), new LinkProperties(linkProperties),
4128            new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler,
4129            networkMisc);
4130        synchronized (this) {
4131            nai.networkMonitor.systemReady = mSystemReady;
4132        }
4133        if (VDBG) log("registerNetworkAgent " + nai);
4134        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
4135    }
4136
4137    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4138        if (VDBG) log("Got NetworkAgent Messenger");
4139        mNetworkAgentInfos.put(na.messenger, na);
4140        synchronized (mNetworkForNetId) {
4141            mNetworkForNetId.put(na.network.netId, na);
4142        }
4143        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4144        NetworkInfo networkInfo = na.networkInfo;
4145        na.networkInfo = null;
4146        updateNetworkInfo(na, networkInfo);
4147    }
4148
4149    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4150        LinkProperties newLp = networkAgent.linkProperties;
4151        int netId = networkAgent.network.netId;
4152
4153        updateInterfaces(newLp, oldLp, netId);
4154        updateMtu(newLp, oldLp);
4155        // TODO - figure out what to do for clat
4156//        for (LinkProperties lp : newLp.getStackedLinks()) {
4157//            updateMtu(lp, null);
4158//        }
4159        final boolean flushDns = updateRoutes(newLp, oldLp, netId);
4160        updateDnses(newLp, oldLp, netId, flushDns);
4161        updateClat(newLp, oldLp, networkAgent);
4162    }
4163
4164    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo na) {
4165        // Update 464xlat state.
4166        if (mClat.requiresClat(na)) {
4167
4168            // If the connection was previously using clat, but is not using it now, stop the clat
4169            // daemon. Normally, this happens automatically when the connection disconnects, but if
4170            // the disconnect is not reported, or if the connection's LinkProperties changed for
4171            // some other reason (e.g., handoff changes the IP addresses on the link), it would
4172            // still be running. If it's not running, then stopping it is a no-op.
4173            if (Nat464Xlat.isRunningClat(oldLp) && !Nat464Xlat.isRunningClat(newLp)) {
4174                mClat.stopClat();
4175            }
4176            // If the link requires clat to be running, then start the daemon now.
4177            if (na.networkInfo.isConnected()) {
4178                mClat.startClat(na);
4179            } else {
4180                mClat.stopClat();
4181            }
4182        }
4183    }
4184
4185    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4186        CompareResult<String> interfaceDiff = new CompareResult<String>();
4187        if (oldLp != null) {
4188            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4189        } else if (newLp != null) {
4190            interfaceDiff.added = newLp.getAllInterfaceNames();
4191        }
4192        for (String iface : interfaceDiff.added) {
4193            try {
4194                mNetd.addInterfaceToNetwork(iface, netId);
4195            } catch (Exception e) {
4196                loge("Exception adding interface: " + e);
4197            }
4198        }
4199        for (String iface : interfaceDiff.removed) {
4200            try {
4201                mNetd.removeInterfaceFromNetwork(iface, netId);
4202            } catch (Exception e) {
4203                loge("Exception removing interface: " + e);
4204            }
4205        }
4206    }
4207
4208    /**
4209     * Have netd update routes from oldLp to newLp.
4210     * @return true if routes changed between oldLp and newLp
4211     */
4212    private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
4213        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4214        if (oldLp != null) {
4215            routeDiff = oldLp.compareAllRoutes(newLp);
4216        } else if (newLp != null) {
4217            routeDiff.added = newLp.getAllRoutes();
4218        }
4219
4220        // add routes before removing old in case it helps with continuous connectivity
4221
4222        // do this twice, adding non-nexthop routes first, then routes they are dependent on
4223        for (RouteInfo route : routeDiff.added) {
4224            if (route.hasGateway()) continue;
4225            try {
4226                mNetd.addRoute(netId, route);
4227            } catch (Exception e) {
4228                loge("Exception in addRoute for non-gateway: " + e);
4229            }
4230        }
4231        for (RouteInfo route : routeDiff.added) {
4232            if (route.hasGateway() == false) continue;
4233            try {
4234                mNetd.addRoute(netId, route);
4235            } catch (Exception e) {
4236                loge("Exception in addRoute for gateway: " + e);
4237            }
4238        }
4239
4240        for (RouteInfo route : routeDiff.removed) {
4241            try {
4242                mNetd.removeRoute(netId, route);
4243            } catch (Exception e) {
4244                loge("Exception in removeRoute: " + e);
4245            }
4246        }
4247        return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
4248    }
4249    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId, boolean flush) {
4250        if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
4251            Collection<InetAddress> dnses = newLp.getDnsServers();
4252            if (dnses.size() == 0 && mDefaultDns != null) {
4253                dnses = new ArrayList();
4254                dnses.add(mDefaultDns);
4255                if (DBG) {
4256                    loge("no dns provided for netId " + netId + ", so using defaults");
4257                }
4258            }
4259            try {
4260                mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4261                    newLp.getDomains());
4262            } catch (Exception e) {
4263                loge("Exception in setDnsServersForNetwork: " + e);
4264            }
4265            NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
4266            if (defaultNai != null && defaultNai.network.netId == netId) {
4267                setDefaultDnsSystemProperties(dnses);
4268            }
4269            flushVmDnsCache();
4270        } else if (flush) {
4271            try {
4272                mNetd.flushNetworkDnsCache(netId);
4273            } catch (Exception e) {
4274                loge("Exception in flushNetworkDnsCache: " + e);
4275            }
4276            flushVmDnsCache();
4277        }
4278    }
4279
4280    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4281        int last = 0;
4282        for (InetAddress dns : dnses) {
4283            ++last;
4284            String key = "net.dns" + last;
4285            String value = dns.getHostAddress();
4286            SystemProperties.set(key, value);
4287        }
4288        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4289            String key = "net.dns" + i;
4290            SystemProperties.set(key, "");
4291        }
4292        mNumDnsEntries = last;
4293    }
4294
4295
4296    private void updateCapabilities(NetworkAgentInfo networkAgent,
4297            NetworkCapabilities networkCapabilities) {
4298        // TODO - what else here?  Verify still satisfies everybody?
4299        // Check if satisfies somebody new?  call callbacks?
4300        synchronized (networkAgent) {
4301            networkAgent.networkCapabilities = networkCapabilities;
4302        }
4303    }
4304
4305    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4306        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
4307        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
4308            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4309                    networkRequest);
4310        }
4311    }
4312
4313    private void callCallbackForRequest(NetworkRequestInfo nri,
4314            NetworkAgentInfo networkAgent, int notificationType) {
4315        if (nri.messenger == null) return;  // Default request has no msgr
4316        Object o;
4317        int a1 = 0;
4318        int a2 = 0;
4319        switch (notificationType) {
4320            case ConnectivityManager.CALLBACK_LOSING:
4321                a1 = 30 * 1000; // TODO - read this from NetworkMonitor
4322                // fall through
4323            case ConnectivityManager.CALLBACK_PRECHECK:
4324            case ConnectivityManager.CALLBACK_AVAILABLE:
4325            case ConnectivityManager.CALLBACK_LOST:
4326            case ConnectivityManager.CALLBACK_CAP_CHANGED:
4327            case ConnectivityManager.CALLBACK_IP_CHANGED: {
4328                o = new NetworkRequest(nri.request);
4329                a2 = networkAgent.network.netId;
4330                break;
4331            }
4332            case ConnectivityManager.CALLBACK_UNAVAIL:
4333            case ConnectivityManager.CALLBACK_RELEASED: {
4334                o = new NetworkRequest(nri.request);
4335                break;
4336            }
4337            default: {
4338                loge("Unknown notificationType " + notificationType);
4339                return;
4340            }
4341        }
4342        Message msg = Message.obtain();
4343        msg.arg1 = a1;
4344        msg.arg2 = a2;
4345        msg.obj = o;
4346        msg.what = notificationType;
4347        try {
4348            if (VDBG) log("sending notification " + notificationType + " for " + nri.request);
4349            nri.messenger.send(msg);
4350        } catch (RemoteException e) {
4351            // may occur naturally in the race of binder death.
4352            loge("RemoteException caught trying to send a callback msg for " + nri.request);
4353        }
4354    }
4355
4356    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4357        if (oldNetwork == null) {
4358            loge("Unknown NetworkAgentInfo in handleLingerComplete");
4359            return;
4360        }
4361        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4362        if (DBG) {
4363            if (oldNetwork.networkRequests.size() != 0) {
4364                loge("Dead network still had " + oldNetwork.networkRequests.size() + " requests");
4365            }
4366        }
4367        oldNetwork.asyncChannel.disconnect();
4368    }
4369
4370    private void makeDefault(NetworkAgentInfo newNetwork) {
4371        if (VDBG) log("Switching to new default network: " + newNetwork);
4372        mActiveDefaultNetwork = newNetwork.networkInfo.getType();
4373        setupDataActivityTracking(newNetwork);
4374        try {
4375            mNetd.setDefaultNetId(newNetwork.network.netId);
4376        } catch (Exception e) {
4377            loge("Exception setting default network :" + e);
4378        }
4379        handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
4380    }
4381
4382    private void handleConnectionValidated(NetworkAgentInfo newNetwork) {
4383        if (newNetwork == null) {
4384            loge("Unknown NetworkAgentInfo in handleConnectionValidated");
4385            return;
4386        }
4387        boolean keep = newNetwork.isVPN();
4388        boolean isNewDefault = false;
4389        if (DBG) log("handleConnectionValidated for "+newNetwork.name());
4390        // check if any NetworkRequest wants this NetworkAgent
4391        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
4392        if (VDBG) log(" new Network has: " + newNetwork.networkCapabilities);
4393        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4394            NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4395            if (newNetwork == currentNetwork) {
4396                if (VDBG) log("Network " + newNetwork.name() + " was already satisfying" +
4397                              " request " + nri.request.requestId + ". No change.");
4398                keep = true;
4399                continue;
4400            }
4401
4402            // check if it satisfies the NetworkCapabilities
4403            if (VDBG) log("  checking if request is satisfied: " + nri.request);
4404            if (nri.request.networkCapabilities.satisfiedByNetworkCapabilities(
4405                    newNetwork.networkCapabilities)) {
4406                // next check if it's better than any current network we're using for
4407                // this request
4408                if (VDBG) {
4409                    log("currentScore = " +
4410                            (currentNetwork != null ? currentNetwork.currentScore : 0) +
4411                            ", newScore = " + newNetwork.currentScore);
4412                }
4413                if (currentNetwork == null ||
4414                        currentNetwork.currentScore < newNetwork.currentScore) {
4415                    if (currentNetwork != null) {
4416                        if (VDBG) log("   accepting network in place of " + currentNetwork.name());
4417                        currentNetwork.networkRequests.remove(nri.request.requestId);
4418                        currentNetwork.networkLingered.add(nri.request);
4419                        affectedNetworks.add(currentNetwork);
4420                    } else {
4421                        if (VDBG) log("   accepting network in place of null");
4422                    }
4423                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
4424                    newNetwork.addRequest(nri.request);
4425                    if (nri.isRequest && nri.request.legacyType != TYPE_NONE) {
4426                        mLegacyTypeTracker.add(nri.request.legacyType, newNetwork);
4427                    }
4428                    keep = true;
4429                    // TODO - this could get expensive if we have alot of requests for this
4430                    // network.  Think about if there is a way to reduce this.  Push
4431                    // netid->request mapping to each factory?
4432                    sendUpdatedScoreToFactories(nri.request, newNetwork.currentScore);
4433                    if (mDefaultRequest.requestId == nri.request.requestId) {
4434                        isNewDefault = true;
4435                        updateActiveDefaultNetwork(newNetwork);
4436                        if (newNetwork.linkProperties != null) {
4437                            setDefaultDnsSystemProperties(
4438                                    newNetwork.linkProperties.getDnsServers());
4439                        } else {
4440                            setDefaultDnsSystemProperties(new ArrayList<InetAddress>());
4441                        }
4442                        // Maintain the illusion: since the legacy API only
4443                        // understands one network at a time, we must pretend
4444                        // that the current default network disconnected before
4445                        // the new one connected.
4446                        if (currentNetwork != null) {
4447                            mLegacyTypeTracker.remove(currentNetwork.networkInfo.getType(),
4448                                                      currentNetwork);
4449                        }
4450                        mDefaultInetConditionPublished = 100;
4451                        mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4452                    }
4453                }
4454            }
4455        }
4456        for (NetworkAgentInfo nai : affectedNetworks) {
4457            boolean teardown = !nai.isVPN();
4458            for (int i = 0; i < nai.networkRequests.size() && teardown; i++) {
4459                NetworkRequest nr = nai.networkRequests.valueAt(i);
4460                try {
4461                if (mNetworkRequests.get(nr).isRequest) {
4462                    teardown = false;
4463                }
4464                } catch (Exception e) {
4465                    loge("Request " + nr + " not found in mNetworkRequests.");
4466                    loge("  it came from request list  of " + nai.name());
4467                }
4468            }
4469            if (teardown) {
4470                nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4471                notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4472            } else {
4473                // not going to linger, so kill the list of linger networks..  only
4474                // notify them of linger if it happens as the result of gaining another,
4475                // but if they transition and old network stays up, don't tell them of linger
4476                // or very delayed loss
4477                nai.networkLingered.clear();
4478                if (VDBG) log("Lingered for " + nai.name() + " cleared");
4479            }
4480        }
4481        if (keep) {
4482            if (isNewDefault) {
4483                makeDefault(newNetwork);
4484                synchronized (ConnectivityService.this) {
4485                    // have a new default network, release the transition wakelock in
4486                    // a second if it's held.  The second pause is to allow apps
4487                    // to reconnect over the new network
4488                    if (mNetTransitionWakeLock.isHeld()) {
4489                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
4490                                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4491                                mNetTransitionWakeLockSerialNumber, 0),
4492                                1000);
4493                    }
4494                }
4495                // TODO - read the tcp buffer size config string from somewhere
4496                // updateNetworkSettings();
4497            }
4498
4499            // Notify battery stats service about this network, both the normal
4500            // interface and any stacked links.
4501            try {
4502                final IBatteryStats bs = BatteryStatsService.getService();
4503                final int type = newNetwork.networkInfo.getType();
4504
4505                final String baseIface = newNetwork.linkProperties.getInterfaceName();
4506                bs.noteNetworkInterfaceType(baseIface, type);
4507                for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4508                    final String stackedIface = stacked.getInterfaceName();
4509                    bs.noteNetworkInterfaceType(stackedIface, type);
4510                    NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4511                }
4512            } catch (RemoteException ignored) {
4513            }
4514
4515            notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4516        } else {
4517            if (DBG && newNetwork.networkRequests.size() != 0) {
4518                loge("tearing down network with live requests:");
4519                for (int i=0; i < newNetwork.networkRequests.size(); i++) {
4520                    loge("  " + newNetwork.networkRequests.valueAt(i));
4521                }
4522            }
4523            if (VDBG) log("Validated network turns out to be unwanted.  Tear it down.");
4524            newNetwork.asyncChannel.disconnect();
4525        }
4526    }
4527
4528
4529    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4530        NetworkInfo.State state = newInfo.getState();
4531        NetworkInfo oldInfo = null;
4532        synchronized (networkAgent) {
4533            oldInfo = networkAgent.networkInfo;
4534            networkAgent.networkInfo = newInfo;
4535        }
4536        if (networkAgent.isVPN() && mLockdownTracker != null) {
4537            mLockdownTracker.onVpnStateChanged(newInfo);
4538        }
4539
4540        if (oldInfo != null && oldInfo.getState() == state) {
4541            if (VDBG) log("ignoring duplicate network state non-change");
4542            return;
4543        }
4544        if (DBG) {
4545            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4546                    (oldInfo == null ? "null" : oldInfo.getState()) +
4547                    " to " + state);
4548        }
4549
4550        if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
4551            try {
4552                // This should never fail.  Specifying an already in use NetID will cause failure.
4553                if (networkAgent.isVPN()) {
4554                    mNetd.createVirtualNetwork(networkAgent.network.netId,
4555                            !networkAgent.linkProperties.getDnsServers().isEmpty(),
4556                            (networkAgent.networkMisc == null ||
4557                                !networkAgent.networkMisc.allowBypass));
4558                } else {
4559                    mNetd.createPhysicalNetwork(networkAgent.network.netId);
4560                }
4561            } catch (Exception e) {
4562                loge("Error creating network " + networkAgent.network.netId + ": "
4563                        + e.getMessage());
4564                return;
4565            }
4566            networkAgent.created = true;
4567            updateLinkProperties(networkAgent, null);
4568            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
4569            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
4570            if (networkAgent.isVPN()) {
4571                // Temporarily disable the default proxy (not global).
4572                synchronized (mProxyLock) {
4573                    if (!mDefaultProxyDisabled) {
4574                        mDefaultProxyDisabled = true;
4575                        if (mGlobalProxy == null && mDefaultProxy != null) {
4576                            sendProxyBroadcast(null);
4577                        }
4578                    }
4579                }
4580                // TODO: support proxy per network.
4581            }
4582            // Make default network if we have no default.  Any network is better than no network.
4583            if (mNetworkForRequestId.get(mDefaultRequest.requestId) == null &&
4584                    networkAgent.isVPN() == false &&
4585                    mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
4586                    networkAgent.networkCapabilities)) {
4587                makeDefault(networkAgent);
4588            }
4589        } else if (state == NetworkInfo.State.DISCONNECTED ||
4590                state == NetworkInfo.State.SUSPENDED) {
4591            networkAgent.asyncChannel.disconnect();
4592            if (networkAgent.isVPN()) {
4593                synchronized (mProxyLock) {
4594                    if (mDefaultProxyDisabled) {
4595                        mDefaultProxyDisabled = false;
4596                        if (mGlobalProxy == null && mDefaultProxy != null) {
4597                            sendProxyBroadcast(mDefaultProxy);
4598                        }
4599                    }
4600                }
4601            }
4602        }
4603    }
4604
4605    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4606        if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
4607
4608        nai.currentScore = score;
4609
4610        // TODO - This will not do the right thing if this network is lowering
4611        // its score and has requests that can be served by other
4612        // currently-active networks, or if the network is increasing its
4613        // score and other networks have requests that can be better served
4614        // by this network.
4615        //
4616        // Really we want to see if any of our requests migrate to other
4617        // active/lingered networks and if any other requests migrate to us (depending
4618        // on increasing/decreasing currentScore.  That's a bit of work and probably our
4619        // score checking/network allocation code needs to be modularized so we can understand
4620        // (see handleConnectionValided for an example).
4621        //
4622        // As a first order approx, lets just advertise the new score to factories.  If
4623        // somebody can beat it they will nominate a network and our normal net replacement
4624        // code will fire.
4625        for (int i = 0; i < nai.networkRequests.size(); i++) {
4626            NetworkRequest nr = nai.networkRequests.valueAt(i);
4627            sendUpdatedScoreToFactories(nr, score);
4628        }
4629    }
4630
4631    // notify only this one new request of the current state
4632    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4633        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4634        // TODO - read state from monitor to decide what to send.
4635//        if (nai.networkMonitor.isLingering()) {
4636//            notifyType = NetworkCallbacks.LOSING;
4637//        } else if (nai.networkMonitor.isEvaluating()) {
4638//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4639//        }
4640        callCallbackForRequest(nri, nai, notifyType);
4641    }
4642
4643    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
4644        // The NetworkInfo we actually send out has no bearing on the real
4645        // state of affairs. For example, if the default connection is mobile,
4646        // and a request for HIPRI has just gone away, we need to pretend that
4647        // HIPRI has just disconnected. So we need to set the type to HIPRI and
4648        // the state to DISCONNECTED, even though the network is of type MOBILE
4649        // and is still connected.
4650        NetworkInfo info = new NetworkInfo(nai.networkInfo);
4651        info.setType(type);
4652        if (connected) {
4653            info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
4654            sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
4655        } else {
4656            info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
4657            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4658            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4659            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4660            if (info.isFailover()) {
4661                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4662                nai.networkInfo.setFailover(false);
4663            }
4664            if (info.getReason() != null) {
4665                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4666            }
4667            if (info.getExtraInfo() != null) {
4668                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4669            }
4670            NetworkAgentInfo newDefaultAgent = null;
4671            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4672                newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4673                if (newDefaultAgent != null) {
4674                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4675                            newDefaultAgent.networkInfo);
4676                } else {
4677                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4678                }
4679            }
4680            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4681                    mDefaultInetConditionPublished);
4682            final Intent immediateIntent = new Intent(intent);
4683            immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
4684            sendStickyBroadcast(immediateIntent);
4685            sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
4686            if (newDefaultAgent != null) {
4687                sendConnectedBroadcastDelayed(newDefaultAgent.networkInfo,
4688                getConnectivityChangeDelay());
4689            }
4690        }
4691    }
4692
4693    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
4694        if (VDBG) log("notifyType " + notifyType + " for " + networkAgent.name());
4695        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
4696            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4697            NetworkRequestInfo nri = mNetworkRequests.get(nr);
4698            if (VDBG) log(" sending notification for " + nr);
4699            callCallbackForRequest(nri, networkAgent, notifyType);
4700        }
4701    }
4702
4703    private LinkProperties getLinkPropertiesForTypeInternal(int networkType) {
4704        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
4705        if (nai != null) {
4706            synchronized (nai) {
4707                return new LinkProperties(nai.linkProperties);
4708            }
4709        }
4710        return new LinkProperties();
4711    }
4712
4713    private NetworkInfo getNetworkInfoForType(int networkType) {
4714        if (!mLegacyTypeTracker.isTypeSupported(networkType))
4715            return null;
4716
4717        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
4718        if (nai != null) {
4719            NetworkInfo result = new NetworkInfo(nai.networkInfo);
4720            result.setType(networkType);
4721            return result;
4722        } else {
4723           return new NetworkInfo(networkType, 0, "Unknown", "");
4724        }
4725    }
4726
4727    private NetworkCapabilities getNetworkCapabilitiesForType(int networkType) {
4728        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
4729        if (nai != null) {
4730            synchronized (nai) {
4731                return new NetworkCapabilities(nai.networkCapabilities);
4732            }
4733        }
4734        return new NetworkCapabilities();
4735    }
4736
4737    @Override
4738    public boolean addVpnAddress(String address, int prefixLength) {
4739        throwIfLockdownEnabled();
4740        int user = UserHandle.getUserId(Binder.getCallingUid());
4741        synchronized (mVpns) {
4742            return mVpns.get(user).addAddress(address, prefixLength);
4743        }
4744    }
4745
4746    @Override
4747    public boolean removeVpnAddress(String address, int prefixLength) {
4748        throwIfLockdownEnabled();
4749        int user = UserHandle.getUserId(Binder.getCallingUid());
4750        synchronized (mVpns) {
4751            return mVpns.get(user).removeAddress(address, prefixLength);
4752        }
4753    }
4754}
4755