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