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