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