ConnectivityService.java revision 5df4bec50495914b47b6a2f73f20d2bd24a9f9ea
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    private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
1747        final NetworkAgentInfo officialNai;
1748        synchronized (mNetworkForNetId) {
1749            officialNai = mNetworkForNetId.get(nai.network.netId);
1750        }
1751        if (officialNai != null && officialNai.equals(nai)) return true;
1752        if (officialNai != null || VDBG) {
1753            loge(msg + " - validateNetworkAgent found mismatched netId: " + officialNai +
1754                " - " + nai);
1755        }
1756        return false;
1757    }
1758
1759    // must be stateless - things change under us.
1760    private class NetworkStateTrackerHandler extends Handler {
1761        public NetworkStateTrackerHandler(Looper looper) {
1762            super(looper);
1763        }
1764
1765        @Override
1766        public void handleMessage(Message msg) {
1767            NetworkInfo info;
1768            switch (msg.what) {
1769                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
1770                    handleAsyncChannelHalfConnect(msg);
1771                    break;
1772                }
1773                case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1774                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1775                    if (nai != null) nai.asyncChannel.disconnect();
1776                    break;
1777                }
1778                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1779                    handleAsyncChannelDisconnected(msg);
1780                    break;
1781                }
1782                case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1783                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1784                    if (nai == null) {
1785                        loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1786                    } else {
1787                        updateCapabilities(nai, (NetworkCapabilities)msg.obj);
1788                    }
1789                    break;
1790                }
1791                case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1792                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1793                    if (nai == null) {
1794                        loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1795                    } else {
1796                        if (VDBG) {
1797                            log("Update of Linkproperties for " + nai.name() +
1798                                    "; created=" + nai.created);
1799                        }
1800                        LinkProperties oldLp = nai.linkProperties;
1801                        synchronized (nai) {
1802                            nai.linkProperties = (LinkProperties)msg.obj;
1803                        }
1804                        if (nai.created) updateLinkProperties(nai, oldLp);
1805                    }
1806                    break;
1807                }
1808                case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1809                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1810                    if (nai == null) {
1811                        loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1812                        break;
1813                    }
1814                    info = (NetworkInfo) msg.obj;
1815                    updateNetworkInfo(nai, info);
1816                    break;
1817                }
1818                case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1819                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1820                    if (nai == null) {
1821                        loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1822                        break;
1823                    }
1824                    Integer score = (Integer) msg.obj;
1825                    if (score != null) updateNetworkScore(nai, score.intValue());
1826                    break;
1827                }
1828                case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1829                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1830                    if (nai == null) {
1831                        loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1832                        break;
1833                    }
1834                    try {
1835                        mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
1836                    } catch (Exception e) {
1837                        // Never crash!
1838                        loge("Exception in addVpnUidRanges: " + e);
1839                    }
1840                    break;
1841                }
1842                case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1843                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1844                    if (nai == null) {
1845                        loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1846                        break;
1847                    }
1848                    try {
1849                        mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
1850                    } catch (Exception e) {
1851                        // Never crash!
1852                        loge("Exception in removeVpnUidRanges: " + e);
1853                    }
1854                    break;
1855                }
1856                case NetworkAgent.EVENT_BLOCK_ADDRESS_FAMILY: {
1857                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1858                    if (nai == null) {
1859                        loge("EVENT_BLOCK_ADDRESS_FAMILY from unknown NetworkAgent");
1860                        break;
1861                    }
1862                    try {
1863                        mNetd.blockAddressFamily((Integer) msg.obj, nai.network.netId,
1864                                nai.linkProperties.getInterfaceName());
1865                    } catch (Exception e) {
1866                        // Never crash!
1867                        loge("Exception in blockAddressFamily: " + e);
1868                    }
1869                    break;
1870                }
1871                case NetworkAgent.EVENT_UNBLOCK_ADDRESS_FAMILY: {
1872                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1873                    if (nai == null) {
1874                        loge("EVENT_UNBLOCK_ADDRESS_FAMILY from unknown NetworkAgent");
1875                        break;
1876                    }
1877                    try {
1878                        mNetd.unblockAddressFamily((Integer) msg.obj, nai.network.netId,
1879                                nai.linkProperties.getInterfaceName());
1880                    } catch (Exception e) {
1881                        // Never crash!
1882                        loge("Exception in blockAddressFamily: " + e);
1883                    }
1884                    break;
1885                }
1886                case NetworkMonitor.EVENT_NETWORK_VALIDATED: {
1887                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
1888                    if (isLiveNetworkAgent(nai, "EVENT_NETWORK_VALIDATED")) {
1889                        handleConnectionValidated(nai);
1890                    }
1891                    break;
1892                }
1893                case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
1894                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
1895                    if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1896                        handleLingerComplete(nai);
1897                    }
1898                    break;
1899                }
1900                case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
1901                    if (msg.arg1 == 0) {
1902                        setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
1903                    } else {
1904                        NetworkAgentInfo nai = null;
1905                        synchronized (mNetworkForNetId) {
1906                            nai = mNetworkForNetId.get(msg.arg2);
1907                        }
1908                        if (nai == null) {
1909                            loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
1910                            break;
1911                        }
1912                        setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
1913                                nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
1914                    }
1915                    break;
1916                }
1917                case NetworkStateTracker.EVENT_STATE_CHANGED: {
1918                    info = (NetworkInfo) msg.obj;
1919                    NetworkInfo.State state = info.getState();
1920
1921                    if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
1922                            (state == NetworkInfo.State.DISCONNECTED) ||
1923                            (state == NetworkInfo.State.SUSPENDED)) {
1924                        log("ConnectivityChange for " +
1925                            info.getTypeName() + ": " +
1926                            state + "/" + info.getDetailedState());
1927                    }
1928
1929                    // Since mobile has the notion of a network/apn that can be used for
1930                    // provisioning we need to check every time we're connected as
1931                    // CaptiveProtalTracker won't detected it because DCT doesn't report it
1932                    // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
1933                    // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
1934                    // is received by MDST and sent here as EVENT_STATE_CHANGED.
1935                    if (ConnectivityManager.isNetworkTypeMobile(info.getType())
1936                            && (0 != Settings.Global.getInt(mContext.getContentResolver(),
1937                                        Settings.Global.DEVICE_PROVISIONED, 0))
1938                            && (((state == NetworkInfo.State.CONNECTED)
1939                                    && (info.getType() == ConnectivityManager.TYPE_MOBILE))
1940                                || info.isConnectedToProvisioningNetwork())) {
1941                        log("ConnectivityChange checkMobileProvisioning for"
1942                                + " TYPE_MOBILE or ProvisioningNetwork");
1943                        checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
1944                    }
1945
1946                    EventLogTags.writeConnectivityStateChanged(
1947                            info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
1948
1949                    if (info.isConnectedToProvisioningNetwork()) {
1950                        /**
1951                         * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
1952                         * for now its an in between network, its a network that
1953                         * is actually a default network but we don't want it to be
1954                         * announced as such to keep background applications from
1955                         * trying to use it. It turns out that some still try so we
1956                         * take the additional step of clearing any default routes
1957                         * to the link that may have incorrectly setup by the lower
1958                         * levels.
1959                         */
1960                        LinkProperties lp = getLinkPropertiesForTypeInternal(info.getType());
1961                        if (DBG) {
1962                            log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
1963                        }
1964
1965                        // Clear any default routes setup by the radio so
1966                        // any activity by applications trying to use this
1967                        // connection will fail until the provisioning network
1968                        // is enabled.
1969                        /*
1970                        for (RouteInfo r : lp.getRoutes()) {
1971                            removeRoute(lp, r, TO_DEFAULT_TABLE,
1972                                        mNetTrackers[info.getType()].getNetwork().netId);
1973                        }
1974                        */
1975                    } else if (state == NetworkInfo.State.DISCONNECTED) {
1976                    } else if (state == NetworkInfo.State.SUSPENDED) {
1977                    } else if (state == NetworkInfo.State.CONNECTED) {
1978                    //    handleConnect(info);
1979                    }
1980                    if (mLockdownTracker != null) {
1981                        mLockdownTracker.onNetworkInfoChanged(info);
1982                    }
1983                    break;
1984                }
1985                case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
1986                    info = (NetworkInfo) msg.obj;
1987                    // TODO: Temporary allowing network configuration
1988                    //       change not resetting sockets.
1989                    //       @see bug/4455071
1990                    /*
1991                    handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()],
1992                            false);
1993                    */
1994                    break;
1995                }
1996            }
1997        }
1998    }
1999
2000    private void handleAsyncChannelHalfConnect(Message msg) {
2001        AsyncChannel ac = (AsyncChannel) msg.obj;
2002        if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
2003            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2004                if (VDBG) log("NetworkFactory connected");
2005                // A network factory has connected.  Send it all current NetworkRequests.
2006                for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2007                    if (nri.isRequest == false) continue;
2008                    NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2009                    ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
2010                            (nai != null ? nai.currentScore : 0), 0, nri.request);
2011                }
2012            } else {
2013                loge("Error connecting NetworkFactory");
2014                mNetworkFactoryInfos.remove(msg.obj);
2015            }
2016        } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2017            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2018                if (VDBG) log("NetworkAgent connected");
2019                // A network agent has requested a connection.  Establish the connection.
2020                mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2021                        sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2022            } else {
2023                loge("Error connecting NetworkAgent");
2024                NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
2025                if (nai != null) {
2026                    synchronized (mNetworkForNetId) {
2027                        mNetworkForNetId.remove(nai.network.netId);
2028                    }
2029                    // Just in case.
2030                    mLegacyTypeTracker.remove(nai);
2031                }
2032            }
2033        }
2034    }
2035    private void handleAsyncChannelDisconnected(Message msg) {
2036        NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2037        if (nai != null) {
2038            if (DBG) {
2039                log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2040            }
2041            // A network agent has disconnected.
2042            if (nai.created) {
2043                // Tell netd to clean up the configuration for this network
2044                // (routing rules, DNS, etc).
2045                try {
2046                    mNetd.removeNetwork(nai.network.netId);
2047                } catch (Exception e) {
2048                    loge("Exception removing network: " + e);
2049                }
2050            }
2051            // TODO - if we move the logic to the network agent (have them disconnect
2052            // because they lost all their requests or because their score isn't good)
2053            // then they would disconnect organically, report their new state and then
2054            // disconnect the channel.
2055            if (nai.networkInfo.isConnected()) {
2056                nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2057                        null, null);
2058            }
2059            if (isDefaultNetwork(nai)) {
2060                mDefaultInetConditionPublished = 0;
2061            }
2062            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2063            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2064            mNetworkAgentInfos.remove(msg.replyTo);
2065            updateClat(null, nai.linkProperties, nai);
2066            mLegacyTypeTracker.remove(nai);
2067            synchronized (mNetworkForNetId) {
2068                mNetworkForNetId.remove(nai.network.netId);
2069            }
2070            // Since we've lost the network, go through all the requests that
2071            // it was satisfying and see if any other factory can satisfy them.
2072            final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
2073            for (int i = 0; i < nai.networkRequests.size(); i++) {
2074                NetworkRequest request = nai.networkRequests.valueAt(i);
2075                NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2076                if (VDBG) {
2077                    log(" checking request " + request + ", currentNetwork = " +
2078                            (currentNetwork != null ? currentNetwork.name() : "null"));
2079                }
2080                if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2081                    mNetworkForRequestId.remove(request.requestId);
2082                    sendUpdatedScoreToFactories(request, 0);
2083                    NetworkAgentInfo alternative = null;
2084                    for (Map.Entry entry : mNetworkAgentInfos.entrySet()) {
2085                        NetworkAgentInfo existing = (NetworkAgentInfo)entry.getValue();
2086                        if (existing.networkInfo.isConnected() &&
2087                                request.networkCapabilities.satisfiedByNetworkCapabilities(
2088                                existing.networkCapabilities) &&
2089                                (alternative == null ||
2090                                 alternative.currentScore < existing.currentScore)) {
2091                            alternative = existing;
2092                        }
2093                    }
2094                    if (alternative != null && !toActivate.contains(alternative)) {
2095                        toActivate.add(alternative);
2096                    }
2097                }
2098            }
2099            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2100                removeDataActivityTracking(nai);
2101                mActiveDefaultNetwork = ConnectivityManager.TYPE_NONE;
2102                requestNetworkTransitionWakelock(nai.name());
2103            }
2104            for (NetworkAgentInfo networkToActivate : toActivate) {
2105                networkToActivate.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2106            }
2107        }
2108    }
2109
2110    private void handleRegisterNetworkRequest(Message msg) {
2111        final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2112        final NetworkCapabilities newCap = nri.request.networkCapabilities;
2113        int score = 0;
2114
2115        // Check for the best currently alive network that satisfies this request
2116        NetworkAgentInfo bestNetwork = null;
2117        for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
2118            if (VDBG) log("handleRegisterNetworkRequest checking " + network.name());
2119            if (newCap.satisfiedByNetworkCapabilities(network.networkCapabilities)) {
2120                if (VDBG) log("apparently satisfied.  currentScore=" + network.currentScore);
2121                if ((bestNetwork == null) || bestNetwork.currentScore < network.currentScore) {
2122                    if (!nri.isRequest) {
2123                        // Not setting bestNetwork here as a listening NetworkRequest may be
2124                        // satisfied by multiple Networks.  Instead the request is added to
2125                        // each satisfying Network and notified about each.
2126                        network.addRequest(nri.request);
2127                        notifyNetworkCallback(network, nri);
2128                    } else {
2129                        bestNetwork = network;
2130                    }
2131                }
2132            }
2133        }
2134        if (bestNetwork != null) {
2135            if (VDBG) log("using " + bestNetwork.name());
2136            if (bestNetwork.networkInfo.isConnected()) {
2137                // Cancel any lingering so the linger timeout doesn't teardown this network
2138                // even though we have a request for it.
2139                bestNetwork.networkLingered.clear();
2140                bestNetwork.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2141            }
2142            bestNetwork.addRequest(nri.request);
2143            mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
2144            notifyNetworkCallback(bestNetwork, nri);
2145            score = bestNetwork.currentScore;
2146            if (nri.request.legacyType != TYPE_NONE) {
2147                mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2148            }
2149        }
2150        mNetworkRequests.put(nri.request, nri);
2151        if (nri.isRequest) {
2152            if (DBG) log("sending new NetworkRequest to factories");
2153            for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2154                nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
2155                        0, nri.request);
2156            }
2157        }
2158    }
2159
2160    private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2161        NetworkRequestInfo nri = mNetworkRequests.get(request);
2162        if (nri != null) {
2163            if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
2164                if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2165                return;
2166            }
2167            if (DBG) log("releasing NetworkRequest " + request);
2168            nri.unlinkDeathRecipient();
2169            mNetworkRequests.remove(request);
2170            // tell the network currently servicing this that it's no longer interested
2171            NetworkAgentInfo affectedNetwork = mNetworkForRequestId.get(nri.request.requestId);
2172            if (affectedNetwork != null) {
2173                mNetworkForRequestId.remove(nri.request.requestId);
2174                affectedNetwork.networkRequests.remove(nri.request.requestId);
2175                if (VDBG) {
2176                    log(" Removing from current network " + affectedNetwork.name() + ", leaving " +
2177                            affectedNetwork.networkRequests.size() + " requests.");
2178                }
2179                if (nri.isRequest && nri.request.legacyType != TYPE_NONE) {
2180                    mLegacyTypeTracker.remove(nri.request.legacyType, affectedNetwork);
2181                }
2182            }
2183
2184            if (nri.isRequest) {
2185                for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2186                    nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2187                            nri.request);
2188                }
2189
2190                if (affectedNetwork != null) {
2191                    // check if this network still has live requests - otherwise, tear down
2192                    // TODO - probably push this to the NF/NA
2193                    boolean keep = affectedNetwork.isVPN();
2194                    for (int i = 0; i < affectedNetwork.networkRequests.size() && !keep; i++) {
2195                        NetworkRequest r = affectedNetwork.networkRequests.valueAt(i);
2196                        if (mNetworkRequests.get(r).isRequest) {
2197                            keep = true;
2198                        }
2199                    }
2200                    if (keep == false) {
2201                        if (DBG) log("no live requests for " + affectedNetwork.name() +
2202                                "; disconnecting");
2203                        affectedNetwork.asyncChannel.disconnect();
2204                    }
2205                }
2206            }
2207            callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2208        }
2209    }
2210
2211    private class InternalHandler extends Handler {
2212        public InternalHandler(Looper looper) {
2213            super(looper);
2214        }
2215
2216        @Override
2217        public void handleMessage(Message msg) {
2218            NetworkInfo info;
2219            switch (msg.what) {
2220                case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
2221                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
2222                    String causedBy = null;
2223                    synchronized (ConnectivityService.this) {
2224                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2225                                mNetTransitionWakeLock.isHeld()) {
2226                            mNetTransitionWakeLock.release();
2227                            causedBy = mNetTransitionWakeLockCausedBy;
2228                        } else {
2229                            break;
2230                        }
2231                    }
2232                    if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2233                        log("Failed to find a new network - expiring NetTransition Wakelock");
2234                    } else {
2235                        log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2236                                " cleared because we found a replacement network");
2237                    }
2238                    break;
2239                }
2240                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
2241                    handleDeprecatedGlobalHttpProxy();
2242                    break;
2243                }
2244                case EVENT_SET_DEPENDENCY_MET: {
2245                    boolean met = (msg.arg1 == ENABLED);
2246                    handleSetDependencyMet(msg.arg2, met);
2247                    break;
2248                }
2249                case EVENT_SEND_STICKY_BROADCAST_INTENT: {
2250                    Intent intent = (Intent)msg.obj;
2251                    sendStickyBroadcast(intent);
2252                    break;
2253                }
2254                case EVENT_SET_POLICY_DATA_ENABLE: {
2255                    final int networkType = msg.arg1;
2256                    final boolean enabled = msg.arg2 == ENABLED;
2257                    handleSetPolicyDataEnable(networkType, enabled);
2258                    break;
2259                }
2260                case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
2261                    int tag = mEnableFailFastMobileDataTag.get();
2262                    if (msg.arg1 == tag) {
2263                        MobileDataStateTracker mobileDst =
2264                            (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
2265                        if (mobileDst != null) {
2266                            mobileDst.setEnableFailFastMobileData(msg.arg2);
2267                        }
2268                    } else {
2269                        log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
2270                                + " != tag:" + tag);
2271                    }
2272                    break;
2273                }
2274                case EVENT_SAMPLE_INTERVAL_ELAPSED: {
2275                    handleNetworkSamplingTimeout();
2276                    break;
2277                }
2278                case EVENT_PROXY_HAS_CHANGED: {
2279                    handleApplyDefaultProxy((ProxyInfo)msg.obj);
2280                    break;
2281                }
2282                case EVENT_REGISTER_NETWORK_FACTORY: {
2283                    handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2284                    break;
2285                }
2286                case EVENT_UNREGISTER_NETWORK_FACTORY: {
2287                    handleUnregisterNetworkFactory((Messenger)msg.obj);
2288                    break;
2289                }
2290                case EVENT_REGISTER_NETWORK_AGENT: {
2291                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2292                    break;
2293                }
2294                case EVENT_REGISTER_NETWORK_REQUEST:
2295                case EVENT_REGISTER_NETWORK_LISTENER: {
2296                    handleRegisterNetworkRequest(msg);
2297                    break;
2298                }
2299                case EVENT_RELEASE_NETWORK_REQUEST: {
2300                    handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
2301                    break;
2302                }
2303                case EVENT_SYSTEM_READY: {
2304                    for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2305                        nai.networkMonitor.systemReady = true;
2306                    }
2307                    break;
2308                }
2309            }
2310        }
2311    }
2312
2313    // javadoc from interface
2314    public int tether(String iface) {
2315        enforceTetherChangePermission();
2316
2317        if (isTetheringSupported()) {
2318            return mTethering.tether(iface);
2319        } else {
2320            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2321        }
2322    }
2323
2324    // javadoc from interface
2325    public int untether(String iface) {
2326        enforceTetherChangePermission();
2327
2328        if (isTetheringSupported()) {
2329            return mTethering.untether(iface);
2330        } else {
2331            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2332        }
2333    }
2334
2335    // javadoc from interface
2336    public int getLastTetherError(String iface) {
2337        enforceTetherAccessPermission();
2338
2339        if (isTetheringSupported()) {
2340            return mTethering.getLastTetherError(iface);
2341        } else {
2342            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2343        }
2344    }
2345
2346    // TODO - proper iface API for selection by property, inspection, etc
2347    public String[] getTetherableUsbRegexs() {
2348        enforceTetherAccessPermission();
2349        if (isTetheringSupported()) {
2350            return mTethering.getTetherableUsbRegexs();
2351        } else {
2352            return new String[0];
2353        }
2354    }
2355
2356    public String[] getTetherableWifiRegexs() {
2357        enforceTetherAccessPermission();
2358        if (isTetheringSupported()) {
2359            return mTethering.getTetherableWifiRegexs();
2360        } else {
2361            return new String[0];
2362        }
2363    }
2364
2365    public String[] getTetherableBluetoothRegexs() {
2366        enforceTetherAccessPermission();
2367        if (isTetheringSupported()) {
2368            return mTethering.getTetherableBluetoothRegexs();
2369        } else {
2370            return new String[0];
2371        }
2372    }
2373
2374    public int setUsbTethering(boolean enable) {
2375        enforceTetherChangePermission();
2376        if (isTetheringSupported()) {
2377            return mTethering.setUsbTethering(enable);
2378        } else {
2379            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2380        }
2381    }
2382
2383    // TODO - move iface listing, queries, etc to new module
2384    // javadoc from interface
2385    public String[] getTetherableIfaces() {
2386        enforceTetherAccessPermission();
2387        return mTethering.getTetherableIfaces();
2388    }
2389
2390    public String[] getTetheredIfaces() {
2391        enforceTetherAccessPermission();
2392        return mTethering.getTetheredIfaces();
2393    }
2394
2395    public String[] getTetheringErroredIfaces() {
2396        enforceTetherAccessPermission();
2397        return mTethering.getErroredIfaces();
2398    }
2399
2400    public String[] getTetheredDhcpRanges() {
2401        enforceConnectivityInternalPermission();
2402        return mTethering.getTetheredDhcpRanges();
2403    }
2404
2405    // if ro.tether.denied = true we default to no tethering
2406    // gservices could set the secure setting to 1 though to enable it on a build where it
2407    // had previously been turned off.
2408    public boolean isTetheringSupported() {
2409        enforceTetherAccessPermission();
2410        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2411        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2412                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2413                && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
2414        return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2415                mTethering.getTetherableWifiRegexs().length != 0 ||
2416                mTethering.getTetherableBluetoothRegexs().length != 0) &&
2417                mTethering.getUpstreamIfaceTypes().length != 0);
2418    }
2419
2420    // Called when we lose the default network and have no replacement yet.
2421    // This will automatically be cleared after X seconds or a new default network
2422    // becomes CONNECTED, whichever happens first.  The timer is started by the
2423    // first caller and not restarted by subsequent callers.
2424    private void requestNetworkTransitionWakelock(String forWhom) {
2425        int serialNum = 0;
2426        synchronized (this) {
2427            if (mNetTransitionWakeLock.isHeld()) return;
2428            serialNum = ++mNetTransitionWakeLockSerialNumber;
2429            mNetTransitionWakeLock.acquire();
2430            mNetTransitionWakeLockCausedBy = forWhom;
2431        }
2432        mHandler.sendMessageDelayed(mHandler.obtainMessage(
2433                EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
2434                mNetTransitionWakeLockTimeout);
2435        return;
2436    }
2437
2438    // 100 percent is full good, 0 is full bad.
2439    public void reportInetCondition(int networkType, int percentage) {
2440        if (percentage > 50) return;  // don't handle good network reports
2441        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2442        if (nai != null) reportBadNetwork(nai.network);
2443    }
2444
2445    public void reportBadNetwork(Network network) {
2446        //TODO
2447    }
2448
2449    public ProxyInfo getProxy() {
2450        // this information is already available as a world read/writable jvm property
2451        // so this API change wouldn't have a benifit.  It also breaks the passing
2452        // of proxy info to all the JVMs.
2453        // enforceAccessPermission();
2454        synchronized (mProxyLock) {
2455            ProxyInfo ret = mGlobalProxy;
2456            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2457            return ret;
2458        }
2459    }
2460
2461    public void setGlobalProxy(ProxyInfo proxyProperties) {
2462        enforceConnectivityInternalPermission();
2463
2464        synchronized (mProxyLock) {
2465            if (proxyProperties == mGlobalProxy) return;
2466            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2467            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2468
2469            String host = "";
2470            int port = 0;
2471            String exclList = "";
2472            String pacFileUrl = "";
2473            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
2474                    (proxyProperties.getPacFileUrl() != null))) {
2475                if (!proxyProperties.isValid()) {
2476                    if (DBG)
2477                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2478                    return;
2479                }
2480                mGlobalProxy = new ProxyInfo(proxyProperties);
2481                host = mGlobalProxy.getHost();
2482                port = mGlobalProxy.getPort();
2483                exclList = mGlobalProxy.getExclusionListAsString();
2484                if (proxyProperties.getPacFileUrl() != null) {
2485                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
2486                }
2487            } else {
2488                mGlobalProxy = null;
2489            }
2490            ContentResolver res = mContext.getContentResolver();
2491            final long token = Binder.clearCallingIdentity();
2492            try {
2493                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2494                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2495                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2496                        exclList);
2497                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
2498            } finally {
2499                Binder.restoreCallingIdentity(token);
2500            }
2501        }
2502
2503        if (mGlobalProxy == null) {
2504            proxyProperties = mDefaultProxy;
2505        }
2506        sendProxyBroadcast(proxyProperties);
2507    }
2508
2509    private void loadGlobalProxy() {
2510        ContentResolver res = mContext.getContentResolver();
2511        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2512        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2513        String exclList = Settings.Global.getString(res,
2514                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2515        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2516        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
2517            ProxyInfo proxyProperties;
2518            if (!TextUtils.isEmpty(pacFileUrl)) {
2519                proxyProperties = new ProxyInfo(pacFileUrl);
2520            } else {
2521                proxyProperties = new ProxyInfo(host, port, exclList);
2522            }
2523            if (!proxyProperties.isValid()) {
2524                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2525                return;
2526            }
2527
2528            synchronized (mProxyLock) {
2529                mGlobalProxy = proxyProperties;
2530            }
2531        }
2532    }
2533
2534    public ProxyInfo getGlobalProxy() {
2535        // this information is already available as a world read/writable jvm property
2536        // so this API change wouldn't have a benifit.  It also breaks the passing
2537        // of proxy info to all the JVMs.
2538        // enforceAccessPermission();
2539        synchronized (mProxyLock) {
2540            return mGlobalProxy;
2541        }
2542    }
2543
2544    private void handleApplyDefaultProxy(ProxyInfo proxy) {
2545        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2546                && (proxy.getPacFileUrl() == null)) {
2547            proxy = null;
2548        }
2549        synchronized (mProxyLock) {
2550            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2551            if (mDefaultProxy == proxy) return; // catches repeated nulls
2552            if (proxy != null &&  !proxy.isValid()) {
2553                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2554                return;
2555            }
2556
2557            // This call could be coming from the PacManager, containing the port of the local
2558            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
2559            // global (to get the correct local port), and send a broadcast.
2560            // TODO: Switch PacManager to have its own message to send back rather than
2561            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
2562            if ((mGlobalProxy != null) && (proxy != null) && (proxy.getPacFileUrl() != null)
2563                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2564                mGlobalProxy = proxy;
2565                sendProxyBroadcast(mGlobalProxy);
2566                return;
2567            }
2568            mDefaultProxy = proxy;
2569
2570            if (mGlobalProxy != null) return;
2571            if (!mDefaultProxyDisabled) {
2572                sendProxyBroadcast(proxy);
2573            }
2574        }
2575    }
2576
2577    private void handleDeprecatedGlobalHttpProxy() {
2578        String proxy = Settings.Global.getString(mContext.getContentResolver(),
2579                Settings.Global.HTTP_PROXY);
2580        if (!TextUtils.isEmpty(proxy)) {
2581            String data[] = proxy.split(":");
2582            if (data.length == 0) {
2583                return;
2584            }
2585
2586            String proxyHost =  data[0];
2587            int proxyPort = 8080;
2588            if (data.length > 1) {
2589                try {
2590                    proxyPort = Integer.parseInt(data[1]);
2591                } catch (NumberFormatException e) {
2592                    return;
2593                }
2594            }
2595            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
2596            setGlobalProxy(p);
2597        }
2598    }
2599
2600    private void sendProxyBroadcast(ProxyInfo proxy) {
2601        if (proxy == null) proxy = new ProxyInfo("", 0, "");
2602        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
2603        if (DBG) log("sending Proxy Broadcast for " + proxy);
2604        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2605        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2606            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2607        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2608        final long ident = Binder.clearCallingIdentity();
2609        try {
2610            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2611        } finally {
2612            Binder.restoreCallingIdentity(ident);
2613        }
2614    }
2615
2616    private static class SettingsObserver extends ContentObserver {
2617        private int mWhat;
2618        private Handler mHandler;
2619        SettingsObserver(Handler handler, int what) {
2620            super(handler);
2621            mHandler = handler;
2622            mWhat = what;
2623        }
2624
2625        void observe(Context context) {
2626            ContentResolver resolver = context.getContentResolver();
2627            resolver.registerContentObserver(Settings.Global.getUriFor(
2628                    Settings.Global.HTTP_PROXY), false, this);
2629        }
2630
2631        @Override
2632        public void onChange(boolean selfChange) {
2633            mHandler.obtainMessage(mWhat).sendToTarget();
2634        }
2635    }
2636
2637    private static void log(String s) {
2638        Slog.d(TAG, s);
2639    }
2640
2641    private static void loge(String s) {
2642        Slog.e(TAG, s);
2643    }
2644
2645    int convertFeatureToNetworkType(int networkType, String feature) {
2646        int usedNetworkType = networkType;
2647
2648        if(networkType == ConnectivityManager.TYPE_MOBILE) {
2649            if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2650                usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
2651            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2652                usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2653            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2654                    TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2655                usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
2656            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2657                usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2658            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2659                usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2660            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2661                usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
2662            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2663                usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
2664            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_EMERGENCY)) {
2665                usedNetworkType = ConnectivityManager.TYPE_MOBILE_EMERGENCY;
2666            } else {
2667                Slog.e(TAG, "Can't match any mobile netTracker!");
2668            }
2669        } else if (networkType == ConnectivityManager.TYPE_WIFI) {
2670            if (TextUtils.equals(feature, "p2p")) {
2671                usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
2672            } else {
2673                Slog.e(TAG, "Can't match any wifi netTracker!");
2674            }
2675        } else {
2676            Slog.e(TAG, "Unexpected network type");
2677        }
2678        return usedNetworkType;
2679    }
2680
2681    private static <T> T checkNotNull(T value, String message) {
2682        if (value == null) {
2683            throw new NullPointerException(message);
2684        }
2685        return value;
2686    }
2687
2688    /**
2689     * Prepare for a VPN application. This method is used by VpnDialogs
2690     * and not available in ConnectivityManager. Permissions are checked
2691     * in Vpn class.
2692     * @hide
2693     */
2694    @Override
2695    public boolean prepareVpn(String oldPackage, String newPackage) {
2696        throwIfLockdownEnabled();
2697        int user = UserHandle.getUserId(Binder.getCallingUid());
2698        synchronized(mVpns) {
2699            return mVpns.get(user).prepare(oldPackage, newPackage);
2700        }
2701    }
2702
2703    /**
2704     * Set whether the current VPN package has the ability to launch VPNs without
2705     * user intervention. This method is used by system UIs and not available
2706     * in ConnectivityManager. Permissions are checked in Vpn class.
2707     * @hide
2708     */
2709    @Override
2710    public void setVpnPackageAuthorization(boolean authorized) {
2711        int user = UserHandle.getUserId(Binder.getCallingUid());
2712        synchronized(mVpns) {
2713            mVpns.get(user).setPackageAuthorization(authorized);
2714        }
2715    }
2716
2717    /**
2718     * Configure a TUN interface and return its file descriptor. Parameters
2719     * are encoded and opaque to this class. This method is used by VpnBuilder
2720     * and not available in ConnectivityManager. Permissions are checked in
2721     * Vpn class.
2722     * @hide
2723     */
2724    @Override
2725    public ParcelFileDescriptor establishVpn(VpnConfig config) {
2726        throwIfLockdownEnabled();
2727        int user = UserHandle.getUserId(Binder.getCallingUid());
2728        synchronized(mVpns) {
2729            return mVpns.get(user).establish(config);
2730        }
2731    }
2732
2733    /**
2734     * Start legacy VPN, controlling native daemons as needed. Creates a
2735     * secondary thread to perform connection work, returning quickly.
2736     */
2737    @Override
2738    public void startLegacyVpn(VpnProfile profile) {
2739        throwIfLockdownEnabled();
2740        final LinkProperties egress = getActiveLinkProperties();
2741        if (egress == null) {
2742            throw new IllegalStateException("Missing active network connection");
2743        }
2744        int user = UserHandle.getUserId(Binder.getCallingUid());
2745        synchronized(mVpns) {
2746            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
2747        }
2748    }
2749
2750    /**
2751     * Return the information of the ongoing legacy VPN. This method is used
2752     * by VpnSettings and not available in ConnectivityManager. Permissions
2753     * are checked in Vpn class.
2754     * @hide
2755     */
2756    @Override
2757    public LegacyVpnInfo getLegacyVpnInfo() {
2758        throwIfLockdownEnabled();
2759        int user = UserHandle.getUserId(Binder.getCallingUid());
2760        synchronized(mVpns) {
2761            return mVpns.get(user).getLegacyVpnInfo();
2762        }
2763    }
2764
2765    /**
2766     * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
2767     * not available in ConnectivityManager.
2768     * Permissions are checked in Vpn class.
2769     * @hide
2770     */
2771    @Override
2772    public VpnConfig getVpnConfig() {
2773        int user = UserHandle.getUserId(Binder.getCallingUid());
2774        synchronized(mVpns) {
2775            return mVpns.get(user).getVpnConfig();
2776        }
2777    }
2778
2779    @Override
2780    public boolean updateLockdownVpn() {
2781        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
2782            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
2783            return false;
2784        }
2785
2786        // Tear down existing lockdown if profile was removed
2787        mLockdownEnabled = LockdownVpnTracker.isEnabled();
2788        if (mLockdownEnabled) {
2789            if (!mKeyStore.isUnlocked()) {
2790                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
2791                return false;
2792            }
2793
2794            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
2795            final VpnProfile profile = VpnProfile.decode(
2796                    profileName, mKeyStore.get(Credentials.VPN + profileName));
2797            int user = UserHandle.getUserId(Binder.getCallingUid());
2798            synchronized(mVpns) {
2799                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
2800                            profile));
2801            }
2802        } else {
2803            setLockdownTracker(null);
2804        }
2805
2806        return true;
2807    }
2808
2809    /**
2810     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
2811     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
2812     */
2813    private void setLockdownTracker(LockdownVpnTracker tracker) {
2814        // Shutdown any existing tracker
2815        final LockdownVpnTracker existing = mLockdownTracker;
2816        mLockdownTracker = null;
2817        if (existing != null) {
2818            existing.shutdown();
2819        }
2820
2821        try {
2822            if (tracker != null) {
2823                mNetd.setFirewallEnabled(true);
2824                mNetd.setFirewallInterfaceRule("lo", true);
2825                mLockdownTracker = tracker;
2826                mLockdownTracker.init();
2827            } else {
2828                mNetd.setFirewallEnabled(false);
2829            }
2830        } catch (RemoteException e) {
2831            // ignored; NMS lives inside system_server
2832        }
2833    }
2834
2835    private void throwIfLockdownEnabled() {
2836        if (mLockdownEnabled) {
2837            throw new IllegalStateException("Unavailable in lockdown mode");
2838        }
2839    }
2840
2841    public void supplyMessenger(int networkType, Messenger messenger) {
2842        enforceConnectivityInternalPermission();
2843
2844        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
2845            mNetTrackers[networkType].supplyMessenger(messenger);
2846        }
2847    }
2848
2849    public int findConnectionTypeForIface(String iface) {
2850        enforceConnectivityInternalPermission();
2851
2852        if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
2853
2854        synchronized(mNetworkForNetId) {
2855            for (int i = 0; i < mNetworkForNetId.size(); i++) {
2856                NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
2857                LinkProperties lp = nai.linkProperties;
2858                if (lp != null && iface.equals(lp.getInterfaceName()) && nai.networkInfo != null) {
2859                    return nai.networkInfo.getType();
2860                }
2861            }
2862        }
2863        return ConnectivityManager.TYPE_NONE;
2864    }
2865
2866    /**
2867     * Have mobile data fail fast if enabled.
2868     *
2869     * @param enabled DctConstants.ENABLED/DISABLED
2870     */
2871    private void setEnableFailFastMobileData(int enabled) {
2872        int tag;
2873
2874        if (enabled == DctConstants.ENABLED) {
2875            tag = mEnableFailFastMobileDataTag.incrementAndGet();
2876        } else {
2877            tag = mEnableFailFastMobileDataTag.get();
2878        }
2879        mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
2880                         enabled));
2881    }
2882
2883    private boolean isMobileDataStateTrackerReady() {
2884        MobileDataStateTracker mdst =
2885                (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
2886        return (mdst != null) && (mdst.isReady());
2887    }
2888
2889    /**
2890     * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
2891     */
2892
2893    /**
2894     * No connection was possible to the network.
2895     * This is NOT a warm sim.
2896     */
2897    private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
2898
2899    /**
2900     * A connection was made to the internet, all is well.
2901     * This is NOT a warm sim.
2902     */
2903    private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
2904
2905    /**
2906     * A connection was made but no dns server was available to resolve a name to address.
2907     * This is NOT a warm sim since provisioning network is supported.
2908     */
2909    private static final int CMP_RESULT_CODE_NO_DNS = 2;
2910
2911    /**
2912     * A connection was made but could not open a TCP connection.
2913     * This is NOT a warm sim since provisioning network is supported.
2914     */
2915    private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
2916
2917    /**
2918     * A connection was made but there was a redirection, we appear to be in walled garden.
2919     * This is an indication of a warm sim on a mobile network such as T-Mobile.
2920     */
2921    private static final int CMP_RESULT_CODE_REDIRECTED = 4;
2922
2923    /**
2924     * The mobile network is a provisioning network.
2925     * This is an indication of a warm sim on a mobile network such as AT&T.
2926     */
2927    private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
2928
2929    /**
2930     * The mobile network is provisioning
2931     */
2932    private static final int CMP_RESULT_CODE_IS_PROVISIONING = 6;
2933
2934    private AtomicBoolean mIsProvisioningNetwork = new AtomicBoolean(false);
2935    private AtomicBoolean mIsStartingProvisioning = new AtomicBoolean(false);
2936
2937    private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
2938
2939    @Override
2940    public int checkMobileProvisioning(int suggestedTimeOutMs) {
2941        int timeOutMs = -1;
2942        if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
2943        enforceConnectivityInternalPermission();
2944
2945        final long token = Binder.clearCallingIdentity();
2946        try {
2947            timeOutMs = suggestedTimeOutMs;
2948            if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
2949                timeOutMs = CheckMp.MAX_TIMEOUT_MS;
2950            }
2951
2952            // Check that mobile networks are supported
2953            if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
2954                    || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
2955                if (DBG) log("checkMobileProvisioning: X no mobile network");
2956                return timeOutMs;
2957            }
2958
2959            // If we're already checking don't do it again
2960            // TODO: Add a queue of results...
2961            if (mIsCheckingMobileProvisioning.getAndSet(true)) {
2962                if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
2963                return timeOutMs;
2964            }
2965
2966            // Start off with mobile notification off
2967            setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
2968
2969            CheckMp checkMp = new CheckMp(mContext, this);
2970            CheckMp.CallBack cb = new CheckMp.CallBack() {
2971                @Override
2972                void onComplete(Integer result) {
2973                    if (DBG) log("CheckMp.onComplete: result=" + result);
2974                    NetworkInfo ni =
2975                            mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
2976                    switch(result) {
2977                        case CMP_RESULT_CODE_CONNECTABLE:
2978                        case CMP_RESULT_CODE_NO_CONNECTION:
2979                        case CMP_RESULT_CODE_NO_DNS:
2980                        case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
2981                            if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
2982                            break;
2983                        }
2984                        case CMP_RESULT_CODE_REDIRECTED: {
2985                            if (DBG) log("CheckMp.onComplete: warm sim");
2986                            String url = getMobileProvisioningUrl();
2987                            if (TextUtils.isEmpty(url)) {
2988                                url = getMobileRedirectedProvisioningUrl();
2989                            }
2990                            if (TextUtils.isEmpty(url) == false) {
2991                                if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
2992                                setProvNotificationVisible(true,
2993                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
2994                                        url);
2995                            } else {
2996                                if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
2997                            }
2998                            break;
2999                        }
3000                        case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
3001                            String url = getMobileProvisioningUrl();
3002                            if (TextUtils.isEmpty(url) == false) {
3003                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
3004                                setProvNotificationVisible(true,
3005                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
3006                                        url);
3007                                // Mark that we've got a provisioning network and
3008                                // Disable Mobile Data until user actually starts provisioning.
3009                                mIsProvisioningNetwork.set(true);
3010                                MobileDataStateTracker mdst = (MobileDataStateTracker)
3011                                        mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3012
3013                                // Disable radio until user starts provisioning
3014                                mdst.setRadio(false);
3015                            } else {
3016                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
3017                            }
3018                            break;
3019                        }
3020                        case CMP_RESULT_CODE_IS_PROVISIONING: {
3021                            // FIXME: Need to know when provisioning is done. Probably we can
3022                            // check the completion status if successful we're done if we
3023                            // "timedout" or still connected to provisioning APN turn off data?
3024                            if (DBG) log("CheckMp.onComplete: provisioning started");
3025                            mIsStartingProvisioning.set(false);
3026                            break;
3027                        }
3028                        default: {
3029                            loge("CheckMp.onComplete: ignore unexpected result=" + result);
3030                            break;
3031                        }
3032                    }
3033                    mIsCheckingMobileProvisioning.set(false);
3034                }
3035            };
3036            CheckMp.Params params =
3037                    new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
3038            if (DBG) log("checkMobileProvisioning: params=" + params);
3039            // TODO: Reenable when calls to the now defunct
3040            //       MobileDataStateTracker.isProvisioningNetwork() are removed.
3041            //       This code should be moved to the Telephony code.
3042            // checkMp.execute(params);
3043        } finally {
3044            Binder.restoreCallingIdentity(token);
3045            if (DBG) log("checkMobileProvisioning: X");
3046        }
3047        return timeOutMs;
3048    }
3049
3050    static class CheckMp extends
3051            AsyncTask<CheckMp.Params, Void, Integer> {
3052        private static final String CHECKMP_TAG = "CheckMp";
3053
3054        // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
3055        private static boolean mTestingFailures;
3056
3057        // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
3058        private static final int MAX_LOOPS = 4;
3059
3060        // Number of milli-seconds to complete all of the retires
3061        public static final int MAX_TIMEOUT_MS =  60000;
3062
3063        // The socket should retry only 5 seconds, the default is longer
3064        private static final int SOCKET_TIMEOUT_MS = 5000;
3065
3066        // Sleep time for network errors
3067        private static final int NET_ERROR_SLEEP_SEC = 3;
3068
3069        // Sleep time for network route establishment
3070        private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
3071
3072        // Short sleep time for polling :(
3073        private static final int POLLING_SLEEP_SEC = 1;
3074
3075        private Context mContext;
3076        private ConnectivityService mCs;
3077        private TelephonyManager mTm;
3078        private Params mParams;
3079
3080        /**
3081         * Parameters for AsyncTask.execute
3082         */
3083        static class Params {
3084            private String mUrl;
3085            private long mTimeOutMs;
3086            private CallBack mCb;
3087
3088            Params(String url, long timeOutMs, CallBack cb) {
3089                mUrl = url;
3090                mTimeOutMs = timeOutMs;
3091                mCb = cb;
3092            }
3093
3094            @Override
3095            public String toString() {
3096                return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
3097            }
3098        }
3099
3100        // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
3101        // issued by name or ip address, for Google its by name so when we construct
3102        // this HostnameVerifier we'll pass the original Uri and use it to verify
3103        // the host. If the host name in the original uril fails we'll test the
3104        // hostname parameter just incase things change.
3105        static class CheckMpHostnameVerifier implements HostnameVerifier {
3106            Uri mOrgUri;
3107
3108            CheckMpHostnameVerifier(Uri orgUri) {
3109                mOrgUri = orgUri;
3110            }
3111
3112            @Override
3113            public boolean verify(String hostname, SSLSession session) {
3114                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
3115                String orgUriHost = mOrgUri.getHost();
3116                boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
3117                if (DBG) {
3118                    log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
3119                        + " orgUriHost=" + orgUriHost);
3120                }
3121                return retVal;
3122            }
3123        }
3124
3125        /**
3126         * The call back object passed in Params. onComplete will be called
3127         * on the main thread.
3128         */
3129        abstract static class CallBack {
3130            // Called on the main thread.
3131            abstract void onComplete(Integer result);
3132        }
3133
3134        public CheckMp(Context context, ConnectivityService cs) {
3135            if (Build.IS_DEBUGGABLE) {
3136                mTestingFailures =
3137                        SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
3138            } else {
3139                mTestingFailures = false;
3140            }
3141
3142            mContext = context;
3143            mCs = cs;
3144
3145            // Setup access to TelephonyService we'll be using.
3146            mTm = (TelephonyManager) mContext.getSystemService(
3147                    Context.TELEPHONY_SERVICE);
3148        }
3149
3150        /**
3151         * Get the default url to use for the test.
3152         */
3153        public String getDefaultUrl() {
3154            // See http://go/clientsdns for usage approval
3155            String server = Settings.Global.getString(mContext.getContentResolver(),
3156                    Settings.Global.CAPTIVE_PORTAL_SERVER);
3157            if (server == null) {
3158                server = "clients3.google.com";
3159            }
3160            return "http://" + server + "/generate_204";
3161        }
3162
3163        /**
3164         * Detect if its possible to connect to the http url. DNS based detection techniques
3165         * do not work at all hotspots. The best way to check is to perform a request to
3166         * a known address that fetches the data we expect.
3167         */
3168        private synchronized Integer isMobileOk(Params params) {
3169            Integer result = CMP_RESULT_CODE_NO_CONNECTION;
3170            Uri orgUri = Uri.parse(params.mUrl);
3171            Random rand = new Random();
3172            mParams = params;
3173
3174            if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
3175                result = CMP_RESULT_CODE_NO_CONNECTION;
3176                log("isMobileOk: X not mobile capable result=" + result);
3177                return result;
3178            }
3179
3180            if (mCs.mIsStartingProvisioning.get()) {
3181                result = CMP_RESULT_CODE_IS_PROVISIONING;
3182                log("isMobileOk: X is provisioning result=" + result);
3183                return result;
3184            }
3185
3186            // See if we've already determined we've got a provisioning connection,
3187            // if so we don't need to do anything active.
3188            MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
3189                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3190            boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
3191            log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
3192
3193            MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
3194                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
3195            boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
3196            log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
3197
3198            if (isDefaultProvisioning || isHipriProvisioning) {
3199                result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
3200                log("isMobileOk: X default || hipri is provisioning result=" + result);
3201                return result;
3202            }
3203
3204            try {
3205                // Continue trying to connect until time has run out
3206                long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
3207
3208                if (!mCs.isMobileDataStateTrackerReady()) {
3209                    // Wait for MobileDataStateTracker to be ready.
3210                    if (DBG) log("isMobileOk: mdst is not ready");
3211                    while(SystemClock.elapsedRealtime() < endTime) {
3212                        if (mCs.isMobileDataStateTrackerReady()) {
3213                            // Enable fail fast as we'll do retries here and use a
3214                            // hipri connection so the default connection stays active.
3215                            if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
3216                            mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
3217                            break;
3218                        }
3219                        sleep(POLLING_SLEEP_SEC);
3220                    }
3221                }
3222
3223                log("isMobileOk: start hipri url=" + params.mUrl);
3224
3225                // First wait until we can start using hipri
3226                Binder binder = new Binder();
3227/*
3228                while(SystemClock.elapsedRealtime() < endTime) {
3229                    int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3230                            Phone.FEATURE_ENABLE_HIPRI, binder);
3231                    if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
3232                        || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
3233                            log("isMobileOk: hipri started");
3234                            break;
3235                    }
3236                    if (VDBG) log("isMobileOk: hipri not started yet");
3237                    result = CMP_RESULT_CODE_NO_CONNECTION;
3238                    sleep(POLLING_SLEEP_SEC);
3239                }
3240*/
3241                // Continue trying to connect until time has run out
3242                while(SystemClock.elapsedRealtime() < endTime) {
3243                    try {
3244                        // Wait for hipri to connect.
3245                        // TODO: Don't poll and handle situation where hipri fails
3246                        // because default is retrying. See b/9569540
3247                        NetworkInfo.State state = mCs
3248                                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3249                        if (state != NetworkInfo.State.CONNECTED) {
3250                            if (true/*VDBG*/) {
3251                                log("isMobileOk: not connected ni=" +
3252                                    mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3253                            }
3254                            sleep(POLLING_SLEEP_SEC);
3255                            result = CMP_RESULT_CODE_NO_CONNECTION;
3256                            continue;
3257                        }
3258
3259                        // Hipri has started check if this is a provisioning url
3260                        MobileDataStateTracker mdst = (MobileDataStateTracker)
3261                                mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
3262                        if (mdst.isProvisioningNetwork()) {
3263                            result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
3264                            if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
3265                            return result;
3266                        } else {
3267                            if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
3268                        }
3269
3270                        // Get of the addresses associated with the url host. We need to use the
3271                        // address otherwise HttpURLConnection object will use the name to get
3272                        // the addresses and will try every address but that will bypass the
3273                        // route to host we setup and the connection could succeed as the default
3274                        // interface might be connected to the internet via wifi or other interface.
3275                        InetAddress[] addresses;
3276                        try {
3277                            addresses = InetAddress.getAllByName(orgUri.getHost());
3278                        } catch (UnknownHostException e) {
3279                            result = CMP_RESULT_CODE_NO_DNS;
3280                            log("isMobileOk: X UnknownHostException result=" + result);
3281                            return result;
3282                        }
3283                        log("isMobileOk: addresses=" + inetAddressesToString(addresses));
3284
3285                        // Get the type of addresses supported by this link
3286                        LinkProperties lp = mCs.getLinkPropertiesForTypeInternal(
3287                                ConnectivityManager.TYPE_MOBILE_HIPRI);
3288                        boolean linkHasIpv4 = lp.hasIPv4Address();
3289                        boolean linkHasIpv6 = lp.hasGlobalIPv6Address();
3290                        log("isMobileOk: linkHasIpv4=" + linkHasIpv4
3291                                + " linkHasIpv6=" + linkHasIpv6);
3292
3293                        final ArrayList<InetAddress> validAddresses =
3294                                new ArrayList<InetAddress>(addresses.length);
3295
3296                        for (InetAddress addr : addresses) {
3297                            if (((addr instanceof Inet4Address) && linkHasIpv4) ||
3298                                    ((addr instanceof Inet6Address) && linkHasIpv6)) {
3299                                validAddresses.add(addr);
3300                            }
3301                        }
3302
3303                        if (validAddresses.size() == 0) {
3304                            return CMP_RESULT_CODE_NO_CONNECTION;
3305                        }
3306
3307                        int addrTried = 0;
3308                        while (true) {
3309                            // Loop through at most MAX_LOOPS valid addresses or until
3310                            // we run out of time
3311                            if (addrTried++ >= MAX_LOOPS) {
3312                                log("isMobileOk: too many loops tried - giving up");
3313                                break;
3314                            }
3315                            if (SystemClock.elapsedRealtime() >= endTime) {
3316                                log("isMobileOk: spend too much time - giving up");
3317                                break;
3318                            }
3319
3320                            InetAddress hostAddr = validAddresses.get(rand.nextInt(
3321                                    validAddresses.size()));
3322
3323                            // Make a route to host so we check the specific interface.
3324                            if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
3325                                    hostAddr.getAddress())) {
3326                                // Wait a short time to be sure the route is established ??
3327                                log("isMobileOk:"
3328                                        + " wait to establish route to hostAddr=" + hostAddr);
3329                                sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
3330                            } else {
3331                                log("isMobileOk:"
3332                                        + " could not establish route to hostAddr=" + hostAddr);
3333                                // Wait a short time before the next attempt
3334                                sleep(NET_ERROR_SLEEP_SEC);
3335                                continue;
3336                            }
3337
3338                            // Rewrite the url to have numeric address to use the specific route
3339                            // using http for half the attempts and https for the other half.
3340                            // Doing https first and http second as on a redirected walled garden
3341                            // such as t-mobile uses we get a SocketTimeoutException: "SSL
3342                            // handshake timed out" which we declare as
3343                            // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
3344                            // having http second we will be using logic used for some time.
3345                            URL newUrl;
3346                            String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
3347                            newUrl = new URL(scheme, hostAddr.getHostAddress(),
3348                                        orgUri.getPath());
3349                            log("isMobileOk: newUrl=" + newUrl);
3350
3351                            HttpURLConnection urlConn = null;
3352                            try {
3353                                // Open the connection set the request headers and get the response
3354                                urlConn = (HttpURLConnection)newUrl.openConnection(
3355                                        java.net.Proxy.NO_PROXY);
3356                                if (scheme.equals("https")) {
3357                                    ((HttpsURLConnection)urlConn).setHostnameVerifier(
3358                                            new CheckMpHostnameVerifier(orgUri));
3359                                }
3360                                urlConn.setInstanceFollowRedirects(false);
3361                                urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
3362                                urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
3363                                urlConn.setUseCaches(false);
3364                                urlConn.setAllowUserInteraction(false);
3365                                // Set the "Connection" to "Close" as by default "Keep-Alive"
3366                                // is used which is useless in this case.
3367                                urlConn.setRequestProperty("Connection", "close");
3368                                int responseCode = urlConn.getResponseCode();
3369
3370                                // For debug display the headers
3371                                Map<String, List<String>> headers = urlConn.getHeaderFields();
3372                                log("isMobileOk: headers=" + headers);
3373
3374                                // Close the connection
3375                                urlConn.disconnect();
3376                                urlConn = null;
3377
3378                                if (mTestingFailures) {
3379                                    // Pretend no connection, this tests using http and https
3380                                    result = CMP_RESULT_CODE_NO_CONNECTION;
3381                                    log("isMobileOk: TESTING_FAILURES, pretend no connction");
3382                                    continue;
3383                                }
3384
3385                                if (responseCode == 204) {
3386                                    // Return
3387                                    result = CMP_RESULT_CODE_CONNECTABLE;
3388                                    log("isMobileOk: X got expected responseCode=" + responseCode
3389                                            + " result=" + result);
3390                                    return result;
3391                                } else {
3392                                    // Retry to be sure this was redirected, we've gotten
3393                                    // occasions where a server returned 200 even though
3394                                    // the device didn't have a "warm" sim.
3395                                    log("isMobileOk: not expected responseCode=" + responseCode);
3396                                    // TODO - it would be nice in the single-address case to do
3397                                    // another DNS resolve here, but flushing the cache is a bit
3398                                    // heavy-handed.
3399                                    result = CMP_RESULT_CODE_REDIRECTED;
3400                                }
3401                            } catch (Exception e) {
3402                                log("isMobileOk: HttpURLConnection Exception" + e);
3403                                result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
3404                                if (urlConn != null) {
3405                                    urlConn.disconnect();
3406                                    urlConn = null;
3407                                }
3408                                sleep(NET_ERROR_SLEEP_SEC);
3409                                continue;
3410                            }
3411                        }
3412                        log("isMobileOk: X loops|timed out result=" + result);
3413                        return result;
3414                    } catch (Exception e) {
3415                        log("isMobileOk: Exception e=" + e);
3416                        continue;
3417                    }
3418                }
3419                log("isMobileOk: timed out");
3420            } finally {
3421                log("isMobileOk: F stop hipri");
3422                mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
3423//                mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
3424//                        Phone.FEATURE_ENABLE_HIPRI);
3425
3426                // Wait for hipri to disconnect.
3427                long endTime = SystemClock.elapsedRealtime() + 5000;
3428
3429                while(SystemClock.elapsedRealtime() < endTime) {
3430                    NetworkInfo.State state = mCs
3431                            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
3432                    if (state != NetworkInfo.State.DISCONNECTED) {
3433                        if (VDBG) {
3434                            log("isMobileOk: connected ni=" +
3435                                mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
3436                        }
3437                        sleep(POLLING_SLEEP_SEC);
3438                        continue;
3439                    }
3440                }
3441
3442                log("isMobileOk: X result=" + result);
3443            }
3444            return result;
3445        }
3446
3447        @Override
3448        protected Integer doInBackground(Params... params) {
3449            return isMobileOk(params[0]);
3450        }
3451
3452        @Override
3453        protected void onPostExecute(Integer result) {
3454            log("onPostExecute: result=" + result);
3455            if ((mParams != null) && (mParams.mCb != null)) {
3456                mParams.mCb.onComplete(result);
3457            }
3458        }
3459
3460        private String inetAddressesToString(InetAddress[] addresses) {
3461            StringBuffer sb = new StringBuffer();
3462            boolean firstTime = true;
3463            for(InetAddress addr : addresses) {
3464                if (firstTime) {
3465                    firstTime = false;
3466                } else {
3467                    sb.append(",");
3468                }
3469                sb.append(addr);
3470            }
3471            return sb.toString();
3472        }
3473
3474        private void printNetworkInfo() {
3475            boolean hasIccCard = mTm.hasIccCard();
3476            int simState = mTm.getSimState();
3477            log("hasIccCard=" + hasIccCard
3478                    + " simState=" + simState);
3479            NetworkInfo[] ni = mCs.getAllNetworkInfo();
3480            if (ni != null) {
3481                log("ni.length=" + ni.length);
3482                for (NetworkInfo netInfo: ni) {
3483                    log("netInfo=" + netInfo.toString());
3484                }
3485            } else {
3486                log("no network info ni=null");
3487            }
3488        }
3489
3490        /**
3491         * Sleep for a few seconds then return.
3492         * @param seconds
3493         */
3494        private static void sleep(int seconds) {
3495            long stopTime = System.nanoTime() + (seconds * 1000000000);
3496            long sleepTime;
3497            while ((sleepTime = stopTime - System.nanoTime()) > 0) {
3498                try {
3499                    Thread.sleep(sleepTime / 1000000);
3500                } catch (InterruptedException ignored) {
3501                }
3502            }
3503        }
3504
3505        private static void log(String s) {
3506            Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
3507        }
3508    }
3509
3510    // TODO: Move to ConnectivityManager and make public?
3511    private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
3512            "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
3513
3514    private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
3515        @Override
3516        public void onReceive(Context context, Intent intent) {
3517            if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
3518                handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
3519            }
3520        }
3521    };
3522
3523    private void handleMobileProvisioningAction(String url) {
3524        // Mark notification as not visible
3525        setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
3526
3527        // Check airplane mode
3528        boolean isAirplaneModeOn = Settings.System.getInt(mContext.getContentResolver(),
3529                Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
3530        // If provisioning network and not in airplane mode handle as a special case,
3531        // otherwise launch browser with the intent directly.
3532        if (mIsProvisioningNetwork.get() && !isAirplaneModeOn) {
3533            if (DBG) log("handleMobileProvisioningAction: on prov network enable then launch");
3534            mIsProvisioningNetwork.set(false);
3535//            mIsStartingProvisioning.set(true);
3536//            MobileDataStateTracker mdst = (MobileDataStateTracker)
3537//                    mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3538            // Radio was disabled on CMP_RESULT_CODE_PROVISIONING_NETWORK, enable it here
3539//            mdst.setRadio(true);
3540//            mdst.setEnableFailFastMobileData(DctConstants.ENABLED);
3541//            mdst.enableMobileProvisioning(url);
3542        } else {
3543            if (DBG) log("handleMobileProvisioningAction: not prov network");
3544            mIsProvisioningNetwork.set(false);
3545            // Check for  apps that can handle provisioning first
3546            Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP);
3547            List<String> carrierPackages =
3548                    mTelephonyManager.getCarrierPackageNamesForBroadcastIntent(provisioningIntent);
3549            if (carrierPackages != null && !carrierPackages.isEmpty()) {
3550                if (carrierPackages.size() != 1) {
3551                    if (DBG) log("Multiple matching carrier apps found, launching the first.");
3552                }
3553                provisioningIntent.setPackage(carrierPackages.get(0));
3554                provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3555                        Intent.FLAG_ACTIVITY_NEW_TASK);
3556                mContext.startActivity(provisioningIntent);
3557            } else {
3558                // If no apps exist, use standard URL ACTION_VIEW method
3559                Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
3560                        Intent.CATEGORY_APP_BROWSER);
3561                newIntent.setData(Uri.parse(url));
3562                newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3563                        Intent.FLAG_ACTIVITY_NEW_TASK);
3564                try {
3565                    mContext.startActivity(newIntent);
3566                } catch (ActivityNotFoundException e) {
3567                    loge("handleMobileProvisioningAction: startActivity failed" + e);
3568                }
3569            }
3570        }
3571    }
3572
3573    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3574    private volatile boolean mIsNotificationVisible = false;
3575
3576    private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
3577            String url) {
3578        if (DBG) {
3579            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
3580                + " extraInfo=" + extraInfo + " url=" + url);
3581        }
3582        Intent intent = null;
3583        PendingIntent pendingIntent = null;
3584        if (visible) {
3585            switch (networkType) {
3586                case ConnectivityManager.TYPE_WIFI:
3587                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
3588                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3589                            Intent.FLAG_ACTIVITY_NEW_TASK);
3590                    pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
3591                    break;
3592                case ConnectivityManager.TYPE_MOBILE:
3593                case ConnectivityManager.TYPE_MOBILE_HIPRI:
3594                    intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
3595                    intent.putExtra("EXTRA_URL", url);
3596                    intent.setFlags(0);
3597                    pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
3598                    break;
3599                default:
3600                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
3601                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
3602                            Intent.FLAG_ACTIVITY_NEW_TASK);
3603                    pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
3604                    break;
3605            }
3606        }
3607        // Concatenate the range of types onto the range of NetIDs.
3608        int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3609        setProvNotificationVisibleIntent(visible, id, networkType, extraInfo, pendingIntent);
3610    }
3611
3612    /**
3613     * Show or hide network provisioning notificaitons.
3614     *
3615     * @param id an identifier that uniquely identifies this notification.  This must match
3616     *         between show and hide calls.  We use the NetID value but for legacy callers
3617     *         we concatenate the range of types with the range of NetIDs.
3618     */
3619    private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
3620            String extraInfo, PendingIntent intent) {
3621        if (DBG) {
3622            log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3623                networkType + " extraInfo=" + extraInfo);
3624        }
3625
3626        Resources r = Resources.getSystem();
3627        NotificationManager notificationManager = (NotificationManager) mContext
3628            .getSystemService(Context.NOTIFICATION_SERVICE);
3629
3630        if (visible) {
3631            CharSequence title;
3632            CharSequence details;
3633            int icon;
3634            Notification notification = new Notification();
3635            switch (networkType) {
3636                case ConnectivityManager.TYPE_WIFI:
3637                    title = r.getString(R.string.wifi_available_sign_in, 0);
3638                    details = r.getString(R.string.network_available_sign_in_detailed,
3639                            extraInfo);
3640                    icon = R.drawable.stat_notify_wifi_in_range;
3641                    break;
3642                case ConnectivityManager.TYPE_MOBILE:
3643                case ConnectivityManager.TYPE_MOBILE_HIPRI:
3644                    title = r.getString(R.string.network_available_sign_in, 0);
3645                    // TODO: Change this to pull from NetworkInfo once a printable
3646                    // name has been added to it
3647                    details = mTelephonyManager.getNetworkOperatorName();
3648                    icon = R.drawable.stat_notify_rssi_in_range;
3649                    break;
3650                default:
3651                    title = r.getString(R.string.network_available_sign_in, 0);
3652                    details = r.getString(R.string.network_available_sign_in_detailed,
3653                            extraInfo);
3654                    icon = R.drawable.stat_notify_rssi_in_range;
3655                    break;
3656            }
3657
3658            notification.when = 0;
3659            notification.icon = icon;
3660            notification.flags = Notification.FLAG_AUTO_CANCEL;
3661            notification.tickerText = title;
3662            notification.color = mContext.getResources().getColor(
3663                    com.android.internal.R.color.system_notification_accent_color);
3664            notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
3665            notification.contentIntent = intent;
3666
3667            try {
3668                notificationManager.notify(NOTIFICATION_ID, id, notification);
3669            } catch (NullPointerException npe) {
3670                loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3671                npe.printStackTrace();
3672            }
3673        } else {
3674            try {
3675                notificationManager.cancel(NOTIFICATION_ID, id);
3676            } catch (NullPointerException npe) {
3677                loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3678                npe.printStackTrace();
3679            }
3680        }
3681        mIsNotificationVisible = visible;
3682    }
3683
3684    /** Location to an updatable file listing carrier provisioning urls.
3685     *  An example:
3686     *
3687     * <?xml version="1.0" encoding="utf-8"?>
3688     *  <provisioningUrls>
3689     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
3690     *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3691     *  </provisioningUrls>
3692     */
3693    private static final String PROVISIONING_URL_PATH =
3694            "/data/misc/radio/provisioning_urls.xml";
3695    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3696
3697    /** XML tag for root element. */
3698    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3699    /** XML tag for individual url */
3700    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3701    /** XML tag for redirected url */
3702    private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3703    /** XML attribute for mcc */
3704    private static final String ATTR_MCC = "mcc";
3705    /** XML attribute for mnc */
3706    private static final String ATTR_MNC = "mnc";
3707
3708    private static final int REDIRECTED_PROVISIONING = 1;
3709    private static final int PROVISIONING = 2;
3710
3711    private String getProvisioningUrlBaseFromFile(int type) {
3712        FileReader fileReader = null;
3713        XmlPullParser parser = null;
3714        Configuration config = mContext.getResources().getConfiguration();
3715        String tagType;
3716
3717        switch (type) {
3718            case PROVISIONING:
3719                tagType = TAG_PROVISIONING_URL;
3720                break;
3721            case REDIRECTED_PROVISIONING:
3722                tagType = TAG_REDIRECTED_URL;
3723                break;
3724            default:
3725                throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3726                        type);
3727        }
3728
3729        try {
3730            fileReader = new FileReader(mProvisioningUrlFile);
3731            parser = Xml.newPullParser();
3732            parser.setInput(fileReader);
3733            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3734
3735            while (true) {
3736                XmlUtils.nextElement(parser);
3737
3738                String element = parser.getName();
3739                if (element == null) break;
3740
3741                if (element.equals(tagType)) {
3742                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
3743                    try {
3744                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3745                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
3746                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3747                                parser.next();
3748                                if (parser.getEventType() == XmlPullParser.TEXT) {
3749                                    return parser.getText();
3750                                }
3751                            }
3752                        }
3753                    } catch (NumberFormatException e) {
3754                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3755                    }
3756                }
3757            }
3758            return null;
3759        } catch (FileNotFoundException e) {
3760            loge("Carrier Provisioning Urls file not found");
3761        } catch (XmlPullParserException e) {
3762            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3763        } catch (IOException e) {
3764            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3765        } finally {
3766            if (fileReader != null) {
3767                try {
3768                    fileReader.close();
3769                } catch (IOException e) {}
3770            }
3771        }
3772        return null;
3773    }
3774
3775    @Override
3776    public String getMobileRedirectedProvisioningUrl() {
3777        enforceConnectivityInternalPermission();
3778        String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3779        if (TextUtils.isEmpty(url)) {
3780            url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3781        }
3782        return url;
3783    }
3784
3785    @Override
3786    public String getMobileProvisioningUrl() {
3787        enforceConnectivityInternalPermission();
3788        String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3789        if (TextUtils.isEmpty(url)) {
3790            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3791            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
3792        } else {
3793            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
3794        }
3795        // populate the iccid, imei and phone number in the provisioning url.
3796        if (!TextUtils.isEmpty(url)) {
3797            String phoneNumber = mTelephonyManager.getLine1Number();
3798            if (TextUtils.isEmpty(phoneNumber)) {
3799                phoneNumber = "0000000000";
3800            }
3801            url = String.format(url,
3802                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
3803                    mTelephonyManager.getDeviceId() /* IMEI */,
3804                    phoneNumber /* Phone numer */);
3805        }
3806
3807        return url;
3808    }
3809
3810    @Override
3811    public void setProvisioningNotificationVisible(boolean visible, int networkType,
3812            String extraInfo, String url) {
3813        enforceConnectivityInternalPermission();
3814        setProvNotificationVisible(visible, networkType, extraInfo, url);
3815    }
3816
3817    @Override
3818    public void setAirplaneMode(boolean enable) {
3819        enforceConnectivityInternalPermission();
3820        final long ident = Binder.clearCallingIdentity();
3821        try {
3822            final ContentResolver cr = mContext.getContentResolver();
3823            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3824            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3825            intent.putExtra("state", enable);
3826            mContext.sendBroadcast(intent);
3827        } finally {
3828            Binder.restoreCallingIdentity(ident);
3829        }
3830    }
3831
3832    private void onUserStart(int userId) {
3833        synchronized(mVpns) {
3834            Vpn userVpn = mVpns.get(userId);
3835            if (userVpn != null) {
3836                loge("Starting user already has a VPN");
3837                return;
3838            }
3839            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, this, userId);
3840            mVpns.put(userId, userVpn);
3841        }
3842    }
3843
3844    private void onUserStop(int userId) {
3845        synchronized(mVpns) {
3846            Vpn userVpn = mVpns.get(userId);
3847            if (userVpn == null) {
3848                loge("Stopping user has no VPN");
3849                return;
3850            }
3851            mVpns.delete(userId);
3852        }
3853    }
3854
3855    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3856        @Override
3857        public void onReceive(Context context, Intent intent) {
3858            final String action = intent.getAction();
3859            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3860            if (userId == UserHandle.USER_NULL) return;
3861
3862            if (Intent.ACTION_USER_STARTING.equals(action)) {
3863                onUserStart(userId);
3864            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3865                onUserStop(userId);
3866            }
3867        }
3868    };
3869
3870    @Override
3871    public LinkQualityInfo getLinkQualityInfo(int networkType) {
3872        enforceAccessPermission();
3873        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3874            return mNetTrackers[networkType].getLinkQualityInfo();
3875        } else {
3876            return null;
3877        }
3878    }
3879
3880    @Override
3881    public LinkQualityInfo getActiveLinkQualityInfo() {
3882        enforceAccessPermission();
3883        if (isNetworkTypeValid(mActiveDefaultNetwork) &&
3884                mNetTrackers[mActiveDefaultNetwork] != null) {
3885            return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
3886        } else {
3887            return null;
3888        }
3889    }
3890
3891    @Override
3892    public LinkQualityInfo[] getAllLinkQualityInfo() {
3893        enforceAccessPermission();
3894        final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
3895        for (NetworkStateTracker tracker : mNetTrackers) {
3896            if (tracker != null) {
3897                LinkQualityInfo li = tracker.getLinkQualityInfo();
3898                if (li != null) {
3899                    result.add(li);
3900                }
3901            }
3902        }
3903
3904        return result.toArray(new LinkQualityInfo[result.size()]);
3905    }
3906
3907    /* Infrastructure for network sampling */
3908
3909    private void handleNetworkSamplingTimeout() {
3910
3911        log("Sampling interval elapsed, updating statistics ..");
3912
3913        // initialize list of interfaces ..
3914        Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
3915                new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
3916        for (NetworkStateTracker tracker : mNetTrackers) {
3917            if (tracker != null) {
3918                String ifaceName = tracker.getNetworkInterfaceName();
3919                if (ifaceName != null) {
3920                    mapIfaceToSample.put(ifaceName, null);
3921                }
3922            }
3923        }
3924
3925        // Read samples for all interfaces
3926        SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
3927
3928        // process samples for all networks
3929        for (NetworkStateTracker tracker : mNetTrackers) {
3930            if (tracker != null) {
3931                String ifaceName = tracker.getNetworkInterfaceName();
3932                SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
3933                if (ss != null) {
3934                    // end the previous sampling cycle
3935                    tracker.stopSampling(ss);
3936                    // start a new sampling cycle ..
3937                    tracker.startSampling(ss);
3938                }
3939            }
3940        }
3941
3942        log("Done.");
3943
3944        int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
3945                Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
3946                DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
3947
3948        if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
3949
3950        setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
3951    }
3952
3953    /**
3954     * Sets a network sampling alarm.
3955     */
3956    void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
3957        long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
3958        int alarmType;
3959        if (Resources.getSystem().getBoolean(
3960                R.bool.config_networkSamplingWakesDevice)) {
3961            alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
3962        } else {
3963            alarmType = AlarmManager.ELAPSED_REALTIME;
3964        }
3965        mAlarmManager.set(alarmType, wakeupTime, intent);
3966    }
3967
3968    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3969            new HashMap<Messenger, NetworkFactoryInfo>();
3970    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3971            new HashMap<NetworkRequest, NetworkRequestInfo>();
3972
3973    private static class NetworkFactoryInfo {
3974        public final String name;
3975        public final Messenger messenger;
3976        public final AsyncChannel asyncChannel;
3977
3978        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3979            this.name = name;
3980            this.messenger = messenger;
3981            this.asyncChannel = asyncChannel;
3982        }
3983    }
3984
3985    /**
3986     * Tracks info about the requester.
3987     * Also used to notice when the calling process dies so we can self-expire
3988     */
3989    private class NetworkRequestInfo implements IBinder.DeathRecipient {
3990        static final boolean REQUEST = true;
3991        static final boolean LISTEN = false;
3992
3993        final NetworkRequest request;
3994        IBinder mBinder;
3995        final int mPid;
3996        final int mUid;
3997        final Messenger messenger;
3998        final boolean isRequest;
3999
4000        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
4001            super();
4002            messenger = m;
4003            request = r;
4004            mBinder = binder;
4005            mPid = getCallingPid();
4006            mUid = getCallingUid();
4007            this.isRequest = isRequest;
4008
4009            try {
4010                mBinder.linkToDeath(this, 0);
4011            } catch (RemoteException e) {
4012                binderDied();
4013            }
4014        }
4015
4016        void unlinkDeathRecipient() {
4017            mBinder.unlinkToDeath(this, 0);
4018        }
4019
4020        public void binderDied() {
4021            log("ConnectivityService NetworkRequestInfo binderDied(" +
4022                    request + ", " + mBinder + ")");
4023            releaseNetworkRequest(request);
4024        }
4025
4026        public String toString() {
4027            return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
4028                    mPid + " for " + request;
4029        }
4030    }
4031
4032    @Override
4033    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
4034            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
4035        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
4036                == false) {
4037            enforceConnectivityInternalPermission();
4038        } else {
4039            enforceChangePermission();
4040        }
4041
4042        networkCapabilities = new NetworkCapabilities(networkCapabilities);
4043
4044        // if UID is restricted, don't allow them to bring up metered APNs
4045        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
4046                == false) {
4047            final int uidRules;
4048            synchronized(mRulesLock) {
4049                uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
4050            }
4051            if ((uidRules & RULE_REJECT_METERED) != 0) {
4052                // we could silently fail or we can filter the available nets to only give
4053                // them those they have access to.  Chose the more useful
4054                networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
4055            }
4056        }
4057
4058        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
4059            throw new IllegalArgumentException("Bad timeout specified");
4060        }
4061        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
4062                nextNetworkRequestId());
4063        if (DBG) log("requestNetwork for " + networkRequest);
4064        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
4065                NetworkRequestInfo.REQUEST);
4066
4067        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
4068        if (timeoutMs > 0) {
4069            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
4070                    nri), timeoutMs);
4071        }
4072        return networkRequest;
4073    }
4074
4075    @Override
4076    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4077            PendingIntent operation) {
4078        // TODO
4079        return null;
4080    }
4081
4082    @Override
4083    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4084            Messenger messenger, IBinder binder) {
4085        enforceAccessPermission();
4086
4087        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
4088                networkCapabilities), TYPE_NONE, nextNetworkRequestId());
4089        if (DBG) log("listenForNetwork for " + networkRequest);
4090        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
4091                NetworkRequestInfo.LISTEN);
4092
4093        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4094        return networkRequest;
4095    }
4096
4097    @Override
4098    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4099            PendingIntent operation) {
4100    }
4101
4102    @Override
4103    public void releaseNetworkRequest(NetworkRequest networkRequest) {
4104        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4105                0, networkRequest));
4106    }
4107
4108    @Override
4109    public void registerNetworkFactory(Messenger messenger, String name) {
4110        enforceConnectivityInternalPermission();
4111        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4112        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
4113    }
4114
4115    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
4116        if (VDBG) log("Got NetworkFactory Messenger for " + nfi.name);
4117        mNetworkFactoryInfos.put(nfi.messenger, nfi);
4118        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4119    }
4120
4121    @Override
4122    public void unregisterNetworkFactory(Messenger messenger) {
4123        enforceConnectivityInternalPermission();
4124        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4125    }
4126
4127    private void handleUnregisterNetworkFactory(Messenger messenger) {
4128        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4129        if (nfi == null) {
4130            if (VDBG) log("Failed to find Messenger in unregisterNetworkFactory");
4131            return;
4132        }
4133        if (VDBG) log("unregisterNetworkFactory for " + nfi.name);
4134    }
4135
4136    /**
4137     * NetworkAgentInfo supporting a request by requestId.
4138     * These have already been vetted (their Capabilities satisfy the request)
4139     * and the are the highest scored network available.
4140     * the are keyed off the Requests requestId.
4141     */
4142    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4143            new SparseArray<NetworkAgentInfo>();
4144
4145    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4146            new SparseArray<NetworkAgentInfo>();
4147
4148    // NetworkAgentInfo keyed off its connecting messenger
4149    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
4150    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4151            new HashMap<Messenger, NetworkAgentInfo>();
4152
4153    private final NetworkRequest mDefaultRequest;
4154
4155    private boolean isDefaultNetwork(NetworkAgentInfo nai) {
4156        return mNetworkForRequestId.get(mDefaultRequest.requestId) == nai;
4157    }
4158
4159    public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
4160            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
4161            int currentScore, NetworkMisc networkMisc) {
4162        enforceConnectivityInternalPermission();
4163
4164        NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
4165            new NetworkInfo(networkInfo), new LinkProperties(linkProperties),
4166            new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler,
4167            networkMisc);
4168        synchronized (this) {
4169            nai.networkMonitor.systemReady = mSystemReady;
4170        }
4171        if (VDBG) log("registerNetworkAgent " + nai);
4172        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
4173    }
4174
4175    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4176        if (VDBG) log("Got NetworkAgent Messenger");
4177        mNetworkAgentInfos.put(na.messenger, na);
4178        assignNextNetId(na);
4179        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4180        NetworkInfo networkInfo = na.networkInfo;
4181        na.networkInfo = null;
4182        updateNetworkInfo(na, networkInfo);
4183    }
4184
4185    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4186        LinkProperties newLp = networkAgent.linkProperties;
4187        int netId = networkAgent.network.netId;
4188
4189        updateInterfaces(newLp, oldLp, netId);
4190        updateMtu(newLp, oldLp);
4191        updateTcpBufferSizes(networkAgent);
4192        // TODO - figure out what to do for clat
4193//        for (LinkProperties lp : newLp.getStackedLinks()) {
4194//            updateMtu(lp, null);
4195//        }
4196        final boolean flushDns = updateRoutes(newLp, oldLp, netId);
4197        updateDnses(newLp, oldLp, netId, flushDns);
4198        updateClat(newLp, oldLp, networkAgent);
4199        if (isDefaultNetwork(networkAgent)) handleApplyDefaultProxy(newLp.getHttpProxy());
4200    }
4201
4202    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo na) {
4203        // Update 464xlat state.
4204        if (mClat.requiresClat(na)) {
4205
4206            // If the connection was previously using clat, but is not using it now, stop the clat
4207            // daemon. Normally, this happens automatically when the connection disconnects, but if
4208            // the disconnect is not reported, or if the connection's LinkProperties changed for
4209            // some other reason (e.g., handoff changes the IP addresses on the link), it would
4210            // still be running. If it's not running, then stopping it is a no-op.
4211            if (Nat464Xlat.isRunningClat(oldLp) && !Nat464Xlat.isRunningClat(newLp)) {
4212                mClat.stopClat();
4213            }
4214            // If the link requires clat to be running, then start the daemon now.
4215            if (na.networkInfo.isConnected()) {
4216                mClat.startClat(na);
4217            } else {
4218                mClat.stopClat();
4219            }
4220        }
4221    }
4222
4223    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4224        CompareResult<String> interfaceDiff = new CompareResult<String>();
4225        if (oldLp != null) {
4226            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4227        } else if (newLp != null) {
4228            interfaceDiff.added = newLp.getAllInterfaceNames();
4229        }
4230        for (String iface : interfaceDiff.added) {
4231            try {
4232                mNetd.addInterfaceToNetwork(iface, netId);
4233            } catch (Exception e) {
4234                loge("Exception adding interface: " + e);
4235            }
4236        }
4237        for (String iface : interfaceDiff.removed) {
4238            try {
4239                mNetd.removeInterfaceFromNetwork(iface, netId);
4240            } catch (Exception e) {
4241                loge("Exception removing interface: " + e);
4242            }
4243        }
4244    }
4245
4246    /**
4247     * Have netd update routes from oldLp to newLp.
4248     * @return true if routes changed between oldLp and newLp
4249     */
4250    private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
4251        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4252        if (oldLp != null) {
4253            routeDiff = oldLp.compareAllRoutes(newLp);
4254        } else if (newLp != null) {
4255            routeDiff.added = newLp.getAllRoutes();
4256        }
4257
4258        // add routes before removing old in case it helps with continuous connectivity
4259
4260        // do this twice, adding non-nexthop routes first, then routes they are dependent on
4261        for (RouteInfo route : routeDiff.added) {
4262            if (route.hasGateway()) continue;
4263            try {
4264                mNetd.addRoute(netId, route);
4265            } catch (Exception e) {
4266                loge("Exception in addRoute for non-gateway: " + e);
4267            }
4268        }
4269        for (RouteInfo route : routeDiff.added) {
4270            if (route.hasGateway() == false) continue;
4271            try {
4272                mNetd.addRoute(netId, route);
4273            } catch (Exception e) {
4274                loge("Exception in addRoute for gateway: " + e);
4275            }
4276        }
4277
4278        for (RouteInfo route : routeDiff.removed) {
4279            try {
4280                mNetd.removeRoute(netId, route);
4281            } catch (Exception e) {
4282                loge("Exception in removeRoute: " + e);
4283            }
4284        }
4285        return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
4286    }
4287    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId, boolean flush) {
4288        if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
4289            Collection<InetAddress> dnses = newLp.getDnsServers();
4290            if (dnses.size() == 0 && mDefaultDns != null) {
4291                dnses = new ArrayList();
4292                dnses.add(mDefaultDns);
4293                if (DBG) {
4294                    loge("no dns provided for netId " + netId + ", so using defaults");
4295                }
4296            }
4297            try {
4298                mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4299                    newLp.getDomains());
4300            } catch (Exception e) {
4301                loge("Exception in setDnsServersForNetwork: " + e);
4302            }
4303            NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
4304            if (defaultNai != null && defaultNai.network.netId == netId) {
4305                setDefaultDnsSystemProperties(dnses);
4306            }
4307            flushVmDnsCache();
4308        } else if (flush) {
4309            try {
4310                mNetd.flushNetworkDnsCache(netId);
4311            } catch (Exception e) {
4312                loge("Exception in flushNetworkDnsCache: " + e);
4313            }
4314            flushVmDnsCache();
4315        }
4316    }
4317
4318    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4319        int last = 0;
4320        for (InetAddress dns : dnses) {
4321            ++last;
4322            String key = "net.dns" + last;
4323            String value = dns.getHostAddress();
4324            SystemProperties.set(key, value);
4325        }
4326        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4327            String key = "net.dns" + i;
4328            SystemProperties.set(key, "");
4329        }
4330        mNumDnsEntries = last;
4331    }
4332
4333
4334    private void updateCapabilities(NetworkAgentInfo networkAgent,
4335            NetworkCapabilities networkCapabilities) {
4336        // TODO - what else here?  Verify still satisfies everybody?
4337        // Check if satisfies somebody new?  call callbacks?
4338        synchronized (networkAgent) {
4339            networkAgent.networkCapabilities = networkCapabilities;
4340        }
4341    }
4342
4343    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4344        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
4345        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
4346            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4347                    networkRequest);
4348        }
4349    }
4350
4351    private void callCallbackForRequest(NetworkRequestInfo nri,
4352            NetworkAgentInfo networkAgent, int notificationType) {
4353        if (nri.messenger == null) return;  // Default request has no msgr
4354        Object o;
4355        int a1 = 0;
4356        int a2 = 0;
4357        switch (notificationType) {
4358            case ConnectivityManager.CALLBACK_LOSING:
4359                a1 = 30 * 1000; // TODO - read this from NetworkMonitor
4360                // fall through
4361            case ConnectivityManager.CALLBACK_PRECHECK:
4362            case ConnectivityManager.CALLBACK_AVAILABLE:
4363            case ConnectivityManager.CALLBACK_LOST:
4364            case ConnectivityManager.CALLBACK_CAP_CHANGED:
4365            case ConnectivityManager.CALLBACK_IP_CHANGED: {
4366                o = new NetworkRequest(nri.request);
4367                a2 = networkAgent.network.netId;
4368                break;
4369            }
4370            case ConnectivityManager.CALLBACK_UNAVAIL:
4371            case ConnectivityManager.CALLBACK_RELEASED: {
4372                o = new NetworkRequest(nri.request);
4373                break;
4374            }
4375            default: {
4376                loge("Unknown notificationType " + notificationType);
4377                return;
4378            }
4379        }
4380        Message msg = Message.obtain();
4381        msg.arg1 = a1;
4382        msg.arg2 = a2;
4383        msg.obj = o;
4384        msg.what = notificationType;
4385        try {
4386            if (VDBG) log("sending notification " + notificationType + " for " + nri.request);
4387            nri.messenger.send(msg);
4388        } catch (RemoteException e) {
4389            // may occur naturally in the race of binder death.
4390            loge("RemoteException caught trying to send a callback msg for " + nri.request);
4391        }
4392    }
4393
4394    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4395        if (oldNetwork == null) {
4396            loge("Unknown NetworkAgentInfo in handleLingerComplete");
4397            return;
4398        }
4399        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4400        if (DBG) {
4401            if (oldNetwork.networkRequests.size() != 0) {
4402                loge("Dead network still had " + oldNetwork.networkRequests.size() + " requests");
4403            }
4404        }
4405        oldNetwork.asyncChannel.disconnect();
4406    }
4407
4408    private void makeDefault(NetworkAgentInfo newNetwork) {
4409        if (VDBG) log("Switching to new default network: " + newNetwork);
4410        mActiveDefaultNetwork = newNetwork.networkInfo.getType();
4411        setupDataActivityTracking(newNetwork);
4412        try {
4413            mNetd.setDefaultNetId(newNetwork.network.netId);
4414        } catch (Exception e) {
4415            loge("Exception setting default network :" + e);
4416        }
4417        handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
4418        updateTcpBufferSizes(newNetwork);
4419    }
4420
4421    private void handleConnectionValidated(NetworkAgentInfo newNetwork) {
4422        if (newNetwork == null) {
4423            loge("Unknown NetworkAgentInfo in handleConnectionValidated");
4424            return;
4425        }
4426        boolean keep = newNetwork.isVPN();
4427        boolean isNewDefault = false;
4428        if (DBG) log("handleConnectionValidated for "+newNetwork.name());
4429        // check if any NetworkRequest wants this NetworkAgent
4430        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
4431        if (VDBG) log(" new Network has: " + newNetwork.networkCapabilities);
4432        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4433            NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4434            if (newNetwork == currentNetwork) {
4435                if (VDBG) log("Network " + newNetwork.name() + " was already satisfying" +
4436                              " request " + nri.request.requestId + ". No change.");
4437                keep = true;
4438                continue;
4439            }
4440
4441            // check if it satisfies the NetworkCapabilities
4442            if (VDBG) log("  checking if request is satisfied: " + nri.request);
4443            if (nri.request.networkCapabilities.satisfiedByNetworkCapabilities(
4444                    newNetwork.networkCapabilities)) {
4445                if (!nri.isRequest) {
4446                    newNetwork.addRequest(nri.request);
4447                    continue;
4448                }
4449                // next check if it's better than any current network we're using for
4450                // this request
4451                if (VDBG) {
4452                    log("currentScore = " +
4453                            (currentNetwork != null ? currentNetwork.currentScore : 0) +
4454                            ", newScore = " + newNetwork.currentScore);
4455                }
4456                if (currentNetwork == null ||
4457                        currentNetwork.currentScore < newNetwork.currentScore) {
4458                    if (currentNetwork != null) {
4459                        if (VDBG) log("   accepting network in place of " + currentNetwork.name());
4460                        currentNetwork.networkRequests.remove(nri.request.requestId);
4461                        currentNetwork.networkLingered.add(nri.request);
4462                        affectedNetworks.add(currentNetwork);
4463                    } else {
4464                        if (VDBG) log("   accepting network in place of null");
4465                    }
4466                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
4467                    newNetwork.addRequest(nri.request);
4468                    if (nri.isRequest && nri.request.legacyType != TYPE_NONE) {
4469                        mLegacyTypeTracker.add(nri.request.legacyType, newNetwork);
4470                    }
4471                    keep = true;
4472                    // TODO - this could get expensive if we have alot of requests for this
4473                    // network.  Think about if there is a way to reduce this.  Push
4474                    // netid->request mapping to each factory?
4475                    sendUpdatedScoreToFactories(nri.request, newNetwork.currentScore);
4476                    if (mDefaultRequest.requestId == nri.request.requestId) {
4477                        isNewDefault = true;
4478                        updateActiveDefaultNetwork(newNetwork);
4479                        if (newNetwork.linkProperties != null) {
4480                            updateTcpBufferSizes(newNetwork);
4481                            setDefaultDnsSystemProperties(
4482                                    newNetwork.linkProperties.getDnsServers());
4483                        } else {
4484                            setDefaultDnsSystemProperties(new ArrayList<InetAddress>());
4485                        }
4486                        // Maintain the illusion: since the legacy API only
4487                        // understands one network at a time, we must pretend
4488                        // that the current default network disconnected before
4489                        // the new one connected.
4490                        if (currentNetwork != null) {
4491                            mLegacyTypeTracker.remove(currentNetwork.networkInfo.getType(),
4492                                                      currentNetwork);
4493                        }
4494                        mDefaultInetConditionPublished = 100;
4495                        mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4496                    }
4497                }
4498            }
4499        }
4500        for (NetworkAgentInfo nai : affectedNetworks) {
4501            boolean teardown = !nai.isVPN();
4502            for (int i = 0; i < nai.networkRequests.size() && teardown; i++) {
4503                NetworkRequest nr = nai.networkRequests.valueAt(i);
4504                try {
4505                if (mNetworkRequests.get(nr).isRequest) {
4506                    teardown = false;
4507                }
4508                } catch (Exception e) {
4509                    loge("Request " + nr + " not found in mNetworkRequests.");
4510                    loge("  it came from request list  of " + nai.name());
4511                }
4512            }
4513            if (teardown) {
4514                nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4515                notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4516            } else {
4517                // not going to linger, so kill the list of linger networks..  only
4518                // notify them of linger if it happens as the result of gaining another,
4519                // but if they transition and old network stays up, don't tell them of linger
4520                // or very delayed loss
4521                nai.networkLingered.clear();
4522                if (VDBG) log("Lingered for " + nai.name() + " cleared");
4523            }
4524        }
4525        if (keep) {
4526            if (isNewDefault) {
4527                makeDefault(newNetwork);
4528                synchronized (ConnectivityService.this) {
4529                    // have a new default network, release the transition wakelock in
4530                    // a second if it's held.  The second pause is to allow apps
4531                    // to reconnect over the new network
4532                    if (mNetTransitionWakeLock.isHeld()) {
4533                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
4534                                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4535                                mNetTransitionWakeLockSerialNumber, 0),
4536                                1000);
4537                    }
4538                }
4539            }
4540
4541            // Notify battery stats service about this network, both the normal
4542            // interface and any stacked links.
4543            try {
4544                final IBatteryStats bs = BatteryStatsService.getService();
4545                final int type = newNetwork.networkInfo.getType();
4546
4547                final String baseIface = newNetwork.linkProperties.getInterfaceName();
4548                bs.noteNetworkInterfaceType(baseIface, type);
4549                for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4550                    final String stackedIface = stacked.getInterfaceName();
4551                    bs.noteNetworkInterfaceType(stackedIface, type);
4552                    NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4553                }
4554            } catch (RemoteException ignored) {
4555            }
4556
4557            notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4558        } else {
4559            if (DBG && newNetwork.networkRequests.size() != 0) {
4560                loge("tearing down network with live requests:");
4561                for (int i=0; i < newNetwork.networkRequests.size(); i++) {
4562                    loge("  " + newNetwork.networkRequests.valueAt(i));
4563                }
4564            }
4565            if (VDBG) log("Validated network turns out to be unwanted.  Tear it down.");
4566            newNetwork.asyncChannel.disconnect();
4567        }
4568    }
4569
4570
4571    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4572        NetworkInfo.State state = newInfo.getState();
4573        NetworkInfo oldInfo = null;
4574        synchronized (networkAgent) {
4575            oldInfo = networkAgent.networkInfo;
4576            networkAgent.networkInfo = newInfo;
4577        }
4578        if (networkAgent.isVPN() && mLockdownTracker != null) {
4579            mLockdownTracker.onVpnStateChanged(newInfo);
4580        }
4581
4582        if (oldInfo != null && oldInfo.getState() == state) {
4583            if (VDBG) log("ignoring duplicate network state non-change");
4584            return;
4585        }
4586        if (DBG) {
4587            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4588                    (oldInfo == null ? "null" : oldInfo.getState()) +
4589                    " to " + state);
4590        }
4591
4592        if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
4593            try {
4594                // This should never fail.  Specifying an already in use NetID will cause failure.
4595                if (networkAgent.isVPN()) {
4596                    mNetd.createVirtualNetwork(networkAgent.network.netId,
4597                            !networkAgent.linkProperties.getDnsServers().isEmpty(),
4598                            (networkAgent.networkMisc == null ||
4599                                !networkAgent.networkMisc.allowBypass));
4600                } else {
4601                    mNetd.createPhysicalNetwork(networkAgent.network.netId);
4602                }
4603            } catch (Exception e) {
4604                loge("Error creating network " + networkAgent.network.netId + ": "
4605                        + e.getMessage());
4606                return;
4607            }
4608            networkAgent.created = true;
4609            updateLinkProperties(networkAgent, null);
4610            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
4611            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
4612            if (networkAgent.isVPN()) {
4613                // Temporarily disable the default proxy (not global).
4614                synchronized (mProxyLock) {
4615                    if (!mDefaultProxyDisabled) {
4616                        mDefaultProxyDisabled = true;
4617                        if (mGlobalProxy == null && mDefaultProxy != null) {
4618                            sendProxyBroadcast(null);
4619                        }
4620                    }
4621                }
4622                // TODO: support proxy per network.
4623            }
4624            // Make default network if we have no default.  Any network is better than no network.
4625            if (mNetworkForRequestId.get(mDefaultRequest.requestId) == null &&
4626                    networkAgent.isVPN() == false &&
4627                    mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
4628                    networkAgent.networkCapabilities)) {
4629                makeDefault(networkAgent);
4630            }
4631        } else if (state == NetworkInfo.State.DISCONNECTED ||
4632                state == NetworkInfo.State.SUSPENDED) {
4633            networkAgent.asyncChannel.disconnect();
4634            if (networkAgent.isVPN()) {
4635                synchronized (mProxyLock) {
4636                    if (mDefaultProxyDisabled) {
4637                        mDefaultProxyDisabled = false;
4638                        if (mGlobalProxy == null && mDefaultProxy != null) {
4639                            sendProxyBroadcast(mDefaultProxy);
4640                        }
4641                    }
4642                }
4643            }
4644        }
4645    }
4646
4647    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4648        if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
4649
4650        nai.currentScore = score;
4651
4652        // TODO - This will not do the right thing if this network is lowering
4653        // its score and has requests that can be served by other
4654        // currently-active networks, or if the network is increasing its
4655        // score and other networks have requests that can be better served
4656        // by this network.
4657        //
4658        // Really we want to see if any of our requests migrate to other
4659        // active/lingered networks and if any other requests migrate to us (depending
4660        // on increasing/decreasing currentScore.  That's a bit of work and probably our
4661        // score checking/network allocation code needs to be modularized so we can understand
4662        // (see handleConnectionValided for an example).
4663        //
4664        // As a first order approx, lets just advertise the new score to factories.  If
4665        // somebody can beat it they will nominate a network and our normal net replacement
4666        // code will fire.
4667        for (int i = 0; i < nai.networkRequests.size(); i++) {
4668            NetworkRequest nr = nai.networkRequests.valueAt(i);
4669            sendUpdatedScoreToFactories(nr, score);
4670        }
4671    }
4672
4673    // notify only this one new request of the current state
4674    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4675        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4676        // TODO - read state from monitor to decide what to send.
4677//        if (nai.networkMonitor.isLingering()) {
4678//            notifyType = NetworkCallbacks.LOSING;
4679//        } else if (nai.networkMonitor.isEvaluating()) {
4680//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4681//        }
4682        callCallbackForRequest(nri, nai, notifyType);
4683    }
4684
4685    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
4686        // The NetworkInfo we actually send out has no bearing on the real
4687        // state of affairs. For example, if the default connection is mobile,
4688        // and a request for HIPRI has just gone away, we need to pretend that
4689        // HIPRI has just disconnected. So we need to set the type to HIPRI and
4690        // the state to DISCONNECTED, even though the network is of type MOBILE
4691        // and is still connected.
4692        NetworkInfo info = new NetworkInfo(nai.networkInfo);
4693        info.setType(type);
4694        if (connected) {
4695            info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
4696            sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
4697        } else {
4698            info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
4699            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4700            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4701            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4702            if (info.isFailover()) {
4703                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4704                nai.networkInfo.setFailover(false);
4705            }
4706            if (info.getReason() != null) {
4707                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4708            }
4709            if (info.getExtraInfo() != null) {
4710                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4711            }
4712            NetworkAgentInfo newDefaultAgent = null;
4713            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4714                newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4715                if (newDefaultAgent != null) {
4716                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4717                            newDefaultAgent.networkInfo);
4718                } else {
4719                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4720                }
4721            }
4722            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4723                    mDefaultInetConditionPublished);
4724            final Intent immediateIntent = new Intent(intent);
4725            immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
4726            sendStickyBroadcast(immediateIntent);
4727            sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
4728            if (newDefaultAgent != null) {
4729                sendConnectedBroadcastDelayed(newDefaultAgent.networkInfo,
4730                getConnectivityChangeDelay());
4731            }
4732        }
4733    }
4734
4735    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
4736        if (VDBG) log("notifyType " + notifyType + " for " + networkAgent.name());
4737        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
4738            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4739            NetworkRequestInfo nri = mNetworkRequests.get(nr);
4740            if (VDBG) log(" sending notification for " + nr);
4741            callCallbackForRequest(nri, networkAgent, notifyType);
4742        }
4743    }
4744
4745    private LinkProperties getLinkPropertiesForTypeInternal(int networkType) {
4746        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
4747        if (nai != null) {
4748            synchronized (nai) {
4749                return new LinkProperties(nai.linkProperties);
4750            }
4751        }
4752        return new LinkProperties();
4753    }
4754
4755    private NetworkInfo getNetworkInfoForType(int networkType) {
4756        if (!mLegacyTypeTracker.isTypeSupported(networkType))
4757            return null;
4758
4759        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
4760        if (nai != null) {
4761            NetworkInfo result = new NetworkInfo(nai.networkInfo);
4762            result.setType(networkType);
4763            return result;
4764        } else {
4765            NetworkInfo result = new NetworkInfo(networkType);
4766            result.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
4767            return result;
4768        }
4769    }
4770
4771    private NetworkCapabilities getNetworkCapabilitiesForType(int networkType) {
4772        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
4773        if (nai != null) {
4774            synchronized (nai) {
4775                return new NetworkCapabilities(nai.networkCapabilities);
4776            }
4777        }
4778        return new NetworkCapabilities();
4779    }
4780
4781    @Override
4782    public boolean addVpnAddress(String address, int prefixLength) {
4783        throwIfLockdownEnabled();
4784        int user = UserHandle.getUserId(Binder.getCallingUid());
4785        synchronized (mVpns) {
4786            return mVpns.get(user).addAddress(address, prefixLength);
4787        }
4788    }
4789
4790    @Override
4791    public boolean removeVpnAddress(String address, int prefixLength) {
4792        throwIfLockdownEnabled();
4793        int user = UserHandle.getUserId(Binder.getCallingUid());
4794        synchronized (mVpns) {
4795            return mVpns.get(user).removeAddress(address, prefixLength);
4796        }
4797    }
4798}
4799