ConnectivityService.java revision df2b878ff4e7b4a258588d3a93574c399db78a07
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
1758        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1759        if (nai == null) {
1760            if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1761                if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1762            } else {
1763                if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1764            }
1765            return false;
1766        }
1767
1768        DetailedState netState = nai.networkInfo.getDetailedState();
1769
1770        if ((netState != DetailedState.CONNECTED &&
1771                netState != DetailedState.CAPTIVE_PORTAL_CHECK)) {
1772            if (VDBG) {
1773                log("requestRouteToHostAddress on down network "
1774                        + "(" + networkType + ") - dropped"
1775                        + " netState=" + netState);
1776            }
1777            return false;
1778        }
1779        final int uid = Binder.getCallingUid();
1780        final long token = Binder.clearCallingIdentity();
1781        try {
1782            LinkProperties lp = nai.linkProperties;
1783            boolean ok = modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt,
1784                    nai.network.netId, uid);
1785            if (DBG) log("requestRouteToHostAddress ok=" + ok);
1786            return ok;
1787        } finally {
1788            Binder.restoreCallingIdentity(token);
1789        }
1790    }
1791
1792    private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
1793            boolean exempt, int netId) {
1794        return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt, netId, false, UID_UNUSED);
1795    }
1796
1797    private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable, int netId) {
1798        return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT, netId, false, UID_UNUSED);
1799    }
1800
1801    private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1802            boolean toDefaultTable, boolean exempt, int netId, int uid) {
1803        RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1804        if (bestRoute == null) {
1805            bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1806        } else {
1807            String iface = bestRoute.getInterface();
1808            if (bestRoute.getGateway().equals(addr)) {
1809                // if there is no better route, add the implied hostroute for our gateway
1810                bestRoute = RouteInfo.makeHostRoute(addr, iface);
1811            } else {
1812                // if we will connect to this through another route, add a direct route
1813                // to it's gateway
1814                bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1815            }
1816        }
1817        return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt, netId, true, uid);
1818    }
1819
1820    /*
1821     * TODO: Clean all this stuff up. Once we have UID-based routing, stuff will break due to
1822     *       incorrect tracking of mAddedRoutes, so a cleanup becomes necessary and urgent. But at
1823     *       the same time, there'll be no more need to track mAddedRoutes or mExemptAddresses,
1824     *       or even have the concept of an exempt address, or do things like "selectBestRoute", or
1825     *       determine "default" vs "secondary" table, etc., so the cleanup becomes possible.
1826     */
1827    private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1828            boolean toDefaultTable, boolean exempt, int netId, boolean legacy, int uid) {
1829        if ((lp == null) || (r == null)) {
1830            if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
1831            return false;
1832        }
1833
1834        if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1835            loge("Error modifying route - too much recursion");
1836            return false;
1837        }
1838
1839        String ifaceName = r.getInterface();
1840        if(ifaceName == null) {
1841            loge("Error modifying route - no interface name");
1842            return false;
1843        }
1844        if (r.hasGateway()) {
1845            RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
1846            if (bestRoute != null) {
1847                if (bestRoute.getGateway().equals(r.getGateway())) {
1848                    // if there is no better route, add the implied hostroute for our gateway
1849                    bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
1850                } else {
1851                    // if we will connect to our gateway through another route, add a direct
1852                    // route to it's gateway
1853                    bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1854                                                        bestRoute.getGateway(),
1855                                                        ifaceName);
1856                }
1857                modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt, netId,
1858                        legacy, uid);
1859            }
1860        }
1861        if (doAdd) {
1862            if (VDBG) log("Adding " + r + " for interface " + ifaceName);
1863            try {
1864                if (toDefaultTable) {
1865                    synchronized (mRoutesLock) {
1866                        // only track default table - only one apps can effect
1867                        mAddedRoutes.add(r);
1868                        if (legacy) {
1869                            mNetd.addLegacyRouteForNetId(netId, r, uid);
1870                        } else {
1871                            mNetd.addRoute(netId, r);
1872                        }
1873                        if (exempt) {
1874                            LinkAddress dest = r.getDestination();
1875                            if (!mExemptAddresses.contains(dest)) {
1876                                mNetd.setHostExemption(dest);
1877                                mExemptAddresses.add(dest);
1878                            }
1879                        }
1880                    }
1881                } else {
1882                    if (legacy) {
1883                        mNetd.addLegacyRouteForNetId(netId, r, uid);
1884                    } else {
1885                        mNetd.addRoute(netId, r);
1886                    }
1887                }
1888            } catch (Exception e) {
1889                // never crash - catch them all
1890                if (DBG) loge("Exception trying to add a route: " + e);
1891                return false;
1892            }
1893        } else {
1894            // if we remove this one and there are no more like it, then refcount==0 and
1895            // we can remove it from the table
1896            if (toDefaultTable) {
1897                synchronized (mRoutesLock) {
1898                    mAddedRoutes.remove(r);
1899                    if (mAddedRoutes.contains(r) == false) {
1900                        if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1901                        try {
1902                            if (legacy) {
1903                                mNetd.removeLegacyRouteForNetId(netId, r, uid);
1904                            } else {
1905                                mNetd.removeRoute(netId, r);
1906                            }
1907                            LinkAddress dest = r.getDestination();
1908                            if (mExemptAddresses.contains(dest)) {
1909                                mNetd.clearHostExemption(dest);
1910                                mExemptAddresses.remove(dest);
1911                            }
1912                        } catch (Exception e) {
1913                            // never crash - catch them all
1914                            if (VDBG) loge("Exception trying to remove a route: " + e);
1915                            return false;
1916                        }
1917                    } else {
1918                        if (VDBG) log("not removing " + r + " as it's still in use");
1919                    }
1920                }
1921            } else {
1922                if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1923                try {
1924                    if (legacy) {
1925                        mNetd.removeLegacyRouteForNetId(netId, r, uid);
1926                    } else {
1927                        mNetd.removeRoute(netId, r);
1928                    }
1929                } catch (Exception e) {
1930                    // never crash - catch them all
1931                    if (VDBG) loge("Exception trying to remove a route: " + e);
1932                    return false;
1933                }
1934            }
1935        }
1936        return true;
1937    }
1938
1939    public void setDataDependency(int networkType, boolean met) {
1940        enforceConnectivityInternalPermission();
1941
1942        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1943                (met ? ENABLED : DISABLED), networkType));
1944    }
1945
1946    private void handleSetDependencyMet(int networkType, boolean met) {
1947        if (mNetTrackers[networkType] != null) {
1948            if (DBG) {
1949                log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1950            }
1951            mNetTrackers[networkType].setDependencyMet(met);
1952        }
1953    }
1954
1955    private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1956        @Override
1957        public void onUidRulesChanged(int uid, int uidRules) {
1958            // caller is NPMS, since we only register with them
1959            if (LOGD_RULES) {
1960                log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1961            }
1962
1963            synchronized (mRulesLock) {
1964                // skip update when we've already applied rules
1965                final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1966                if (oldRules == uidRules) return;
1967
1968                mUidRules.put(uid, uidRules);
1969            }
1970
1971            // TODO: notify UID when it has requested targeted updates
1972        }
1973
1974        @Override
1975        public void onMeteredIfacesChanged(String[] meteredIfaces) {
1976            // caller is NPMS, since we only register with them
1977            if (LOGD_RULES) {
1978                log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1979            }
1980
1981            synchronized (mRulesLock) {
1982                mMeteredIfaces.clear();
1983                for (String iface : meteredIfaces) {
1984                    mMeteredIfaces.add(iface);
1985                }
1986            }
1987        }
1988
1989        @Override
1990        public void onRestrictBackgroundChanged(boolean restrictBackground) {
1991            // caller is NPMS, since we only register with them
1992            if (LOGD_RULES) {
1993                log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1994            }
1995
1996            // kick off connectivity change broadcast for active network, since
1997            // global background policy change is radical.
1998            final int networkType = mActiveDefaultNetwork;
1999            if (isNetworkTypeValid(networkType)) {
2000                final NetworkStateTracker tracker = mNetTrackers[networkType];
2001                if (tracker != null) {
2002                    final NetworkInfo info = tracker.getNetworkInfo();
2003                    if (info != null && info.isConnected()) {
2004                        sendConnectedBroadcast(info);
2005                    }
2006                }
2007            }
2008        }
2009    };
2010
2011    @Override
2012    public void setPolicyDataEnable(int networkType, boolean enabled) {
2013        // only someone like NPMS should only be calling us
2014        mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2015
2016        mHandler.sendMessage(mHandler.obtainMessage(
2017                EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
2018    }
2019
2020    private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
2021   // TODO - handle this passing to factories
2022//        if (isNetworkTypeValid(networkType)) {
2023//            final NetworkStateTracker tracker = mNetTrackers[networkType];
2024//            if (tracker != null) {
2025//                tracker.setPolicyDataEnable(enabled);
2026//            }
2027//        }
2028    }
2029
2030    private void enforceAccessPermission() {
2031        mContext.enforceCallingOrSelfPermission(
2032                android.Manifest.permission.ACCESS_NETWORK_STATE,
2033                "ConnectivityService");
2034    }
2035
2036    private void enforceChangePermission() {
2037        mContext.enforceCallingOrSelfPermission(
2038                android.Manifest.permission.CHANGE_NETWORK_STATE,
2039                "ConnectivityService");
2040    }
2041
2042    // TODO Make this a special check when it goes public
2043    private void enforceTetherChangePermission() {
2044        mContext.enforceCallingOrSelfPermission(
2045                android.Manifest.permission.CHANGE_NETWORK_STATE,
2046                "ConnectivityService");
2047    }
2048
2049    private void enforceTetherAccessPermission() {
2050        mContext.enforceCallingOrSelfPermission(
2051                android.Manifest.permission.ACCESS_NETWORK_STATE,
2052                "ConnectivityService");
2053    }
2054
2055    private void enforceConnectivityInternalPermission() {
2056        mContext.enforceCallingOrSelfPermission(
2057                android.Manifest.permission.CONNECTIVITY_INTERNAL,
2058                "ConnectivityService");
2059    }
2060
2061    private void enforceMarkNetworkSocketPermission() {
2062        //Media server special case
2063        if (Binder.getCallingUid() == Process.MEDIA_UID) {
2064            return;
2065        }
2066        mContext.enforceCallingOrSelfPermission(
2067                android.Manifest.permission.MARK_NETWORK_SOCKET,
2068                "ConnectivityService");
2069    }
2070
2071    /**
2072     * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
2073     * network, we ignore it. If it is for the active network, we send out a
2074     * broadcast. But first, we check whether it might be possible to connect
2075     * to a different network.
2076     * @param info the {@code NetworkInfo} for the network
2077     */
2078    private void handleDisconnect(NetworkInfo info) {
2079
2080        int prevNetType = info.getType();
2081
2082        mNetTrackers[prevNetType].setTeardownRequested(false);
2083        int thisNetId = mNetTrackers[prevNetType].getNetwork().netId;
2084
2085        // Remove idletimer previously setup in {@code handleConnect}
2086// Already in place in new function. This is dead code.
2087//        if (mNetConfigs[prevNetType].isDefault()) {
2088//            removeDataActivityTracking(prevNetType);
2089//        }
2090
2091        /*
2092         * If the disconnected network is not the active one, then don't report
2093         * this as a loss of connectivity. What probably happened is that we're
2094         * getting the disconnect for a network that we explicitly disabled
2095         * in accordance with network preference policies.
2096         */
2097        if (!mNetConfigs[prevNetType].isDefault()) {
2098            List<Integer> pids = mNetRequestersPids[prevNetType];
2099            for (Integer pid : pids) {
2100                // will remove them because the net's no longer connected
2101                // need to do this now as only now do we know the pids and
2102                // can properly null things that are no longer referenced.
2103                reassessPidDns(pid.intValue(), false);
2104            }
2105        }
2106
2107        Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
2108        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2109        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2110        if (info.isFailover()) {
2111            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2112            info.setFailover(false);
2113        }
2114        if (info.getReason() != null) {
2115            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2116        }
2117        if (info.getExtraInfo() != null) {
2118            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2119                    info.getExtraInfo());
2120        }
2121
2122        if (mNetConfigs[prevNetType].isDefault()) {
2123            tryFailover(prevNetType);
2124            if (mActiveDefaultNetwork != -1) {
2125                NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2126                intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
2127            } else {
2128                mDefaultInetConditionPublished = 0; // we're not connected anymore
2129                intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
2130            }
2131        }
2132        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2133
2134        // Reset interface if no other connections are using the same interface
2135        boolean doReset = true;
2136        LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
2137        if (linkProperties != null) {
2138            String oldIface = linkProperties.getInterfaceName();
2139            if (TextUtils.isEmpty(oldIface) == false) {
2140                for (NetworkStateTracker networkStateTracker : mNetTrackers) {
2141                    if (networkStateTracker == null) continue;
2142                    NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
2143                    if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
2144                        LinkProperties l = networkStateTracker.getLinkProperties();
2145                        if (l == null) continue;
2146                        if (oldIface.equals(l.getInterfaceName())) {
2147                            doReset = false;
2148                            break;
2149                        }
2150                    }
2151                }
2152            }
2153        }
2154
2155        // do this before we broadcast the change
2156// Already done in new function. This is dead code.
2157//        handleConnectivityChange(prevNetType, doReset);
2158
2159        final Intent immediateIntent = new Intent(intent);
2160        immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
2161        sendStickyBroadcast(immediateIntent);
2162        sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
2163        /*
2164         * If the failover network is already connected, then immediately send
2165         * out a followup broadcast indicating successful failover
2166         */
2167        if (mActiveDefaultNetwork != -1) {
2168            sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
2169                    getConnectivityChangeDelay());
2170        }
2171        try {
2172//            mNetd.removeNetwork(thisNetId);
2173        } catch (Exception e) {
2174            loge("Exception removing network: " + e);
2175        } finally {
2176            mNetTrackers[prevNetType].setNetId(INVALID_NET_ID);
2177        }
2178    }
2179
2180    private void tryFailover(int prevNetType) {
2181        /*
2182         * If this is a default network, check if other defaults are available.
2183         * Try to reconnect on all available and let them hash it out when
2184         * more than one connects.
2185         */
2186        if (mNetConfigs[prevNetType].isDefault()) {
2187            if (mActiveDefaultNetwork == prevNetType) {
2188                if (DBG) {
2189                    log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
2190                }
2191                mActiveDefaultNetwork = -1;
2192                try {
2193                    mNetd.clearDefaultNetId();
2194                } catch (Exception e) {
2195                    loge("Exception clearing default network :" + e);
2196                }
2197            }
2198
2199            // don't signal a reconnect for anything lower or equal priority than our
2200            // current connected default
2201            // TODO - don't filter by priority now - nice optimization but risky
2202//            int currentPriority = -1;
2203//            if (mActiveDefaultNetwork != -1) {
2204//                currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
2205//            }
2206
2207            for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
2208                if (checkType == prevNetType) continue;
2209                if (mNetConfigs[checkType] == null) continue;
2210                if (!mNetConfigs[checkType].isDefault()) continue;
2211                if (mNetTrackers[checkType] == null) continue;
2212
2213// Enabling the isAvailable() optimization caused mobile to not get
2214// selected if it was in the middle of error handling. Specifically
2215// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
2216// would not be available and we wouldn't get connected to anything.
2217// So removing the isAvailable() optimization below for now. TODO: This
2218// optimization should work and we need to investigate why it doesn't work.
2219// This could be related to how DEACTIVATE_DATA_CALL is reporting its
2220// complete before it is really complete.
2221
2222//                if (!mNetTrackers[checkType].isAvailable()) continue;
2223
2224//                if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
2225
2226                NetworkStateTracker checkTracker = mNetTrackers[checkType];
2227                NetworkInfo checkInfo = checkTracker.getNetworkInfo();
2228                if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
2229                    checkInfo.setFailover(true);
2230                    checkTracker.reconnect();
2231                }
2232                if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
2233            }
2234        }
2235    }
2236
2237    public void sendConnectedBroadcast(NetworkInfo info) {
2238        enforceConnectivityInternalPermission();
2239        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2240        sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
2241    }
2242
2243    private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
2244        sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
2245        sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
2246    }
2247
2248    private void sendInetConditionBroadcast(NetworkInfo info) {
2249        sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2250    }
2251
2252    private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
2253        if (mLockdownTracker != null) {
2254            info = mLockdownTracker.augmentNetworkInfo(info);
2255        }
2256
2257        Intent intent = new Intent(bcastType);
2258        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2259        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2260        if (info.isFailover()) {
2261            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2262            info.setFailover(false);
2263        }
2264        if (info.getReason() != null) {
2265            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2266        }
2267        if (info.getExtraInfo() != null) {
2268            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2269                    info.getExtraInfo());
2270        }
2271        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2272        return intent;
2273    }
2274
2275    private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2276        sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2277    }
2278
2279    private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
2280        sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
2281    }
2282
2283    private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
2284        Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
2285        intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
2286        intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
2287        intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
2288        final long ident = Binder.clearCallingIdentity();
2289        try {
2290            mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
2291                    RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
2292        } finally {
2293            Binder.restoreCallingIdentity(ident);
2294        }
2295    }
2296
2297    private void sendStickyBroadcast(Intent intent) {
2298        synchronized(this) {
2299            if (!mSystemReady) {
2300                mInitialBroadcast = new Intent(intent);
2301            }
2302            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2303            if (VDBG) {
2304                log("sendStickyBroadcast: action=" + intent.getAction());
2305            }
2306
2307            final long ident = Binder.clearCallingIdentity();
2308            try {
2309                mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2310            } finally {
2311                Binder.restoreCallingIdentity(ident);
2312            }
2313        }
2314    }
2315
2316    private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
2317        if (delayMs <= 0) {
2318            sendStickyBroadcast(intent);
2319        } else {
2320            if (VDBG) {
2321                log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
2322                        + intent.getAction());
2323            }
2324            mHandler.sendMessageDelayed(mHandler.obtainMessage(
2325                    EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
2326        }
2327    }
2328
2329    void systemReady() {
2330        mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
2331        loadGlobalProxy();
2332
2333        synchronized(this) {
2334            mSystemReady = true;
2335            if (mInitialBroadcast != null) {
2336                mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
2337                mInitialBroadcast = null;
2338            }
2339        }
2340        // load the global proxy at startup
2341        mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
2342
2343        // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2344        // for user to unlock device.
2345        if (!updateLockdownVpn()) {
2346            final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2347            mContext.registerReceiver(mUserPresentReceiver, filter);
2348        }
2349    }
2350
2351    private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2352        @Override
2353        public void onReceive(Context context, Intent intent) {
2354            // Try creating lockdown tracker, since user present usually means
2355            // unlocked keystore.
2356            if (updateLockdownVpn()) {
2357                mContext.unregisterReceiver(this);
2358            }
2359        }
2360    };
2361
2362    private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2363        if (((type != mNetworkPreference)
2364                      && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
2365                   || (mNetworkPreference == mActiveDefaultNetwork)) {
2366            return false;
2367        }
2368        return true;
2369    }
2370
2371    private void handleConnect(NetworkInfo info) {
2372        final int newNetType = info.getType();
2373
2374        // snapshot isFailover, because sendConnectedBroadcast() resets it
2375        boolean isFailover = info.isFailover();
2376        final NetworkStateTracker thisNet = mNetTrackers[newNetType];
2377        final String thisIface = thisNet.getLinkProperties().getInterfaceName();
2378
2379        if (VDBG) {
2380            log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
2381                    + " isFailover" + isFailover);
2382        }
2383
2384        // if this is a default net and other default is running
2385        // kill the one not preferred
2386        if (mNetConfigs[newNetType].isDefault()) {
2387            if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2388                if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
2389                   String teardownPolicy = SystemProperties.get("net.teardownPolicy");
2390                   if (TextUtils.equals(teardownPolicy, "keep") == false) {
2391                        // tear down the other
2392                        NetworkStateTracker otherNet =
2393                                mNetTrackers[mActiveDefaultNetwork];
2394                        if (DBG) {
2395                            log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
2396                                " teardown");
2397                        }
2398                        if (!teardown(otherNet)) {
2399                            loge("Network declined teardown request");
2400                            teardown(thisNet);
2401                            return;
2402                        }
2403                    } else {
2404                        //TODO - remove
2405                        loge("network teardown skipped due to net.teardownPolicy setting");
2406                    }
2407                } else {
2408                       // don't accept this one
2409                        if (VDBG) {
2410                            log("Not broadcasting CONNECT_ACTION " +
2411                                "to torn down network " + info.getTypeName());
2412                        }
2413                        teardown(thisNet);
2414                        return;
2415                }
2416            }
2417            int thisNetId = nextNetId();
2418            thisNet.setNetId(thisNetId);
2419            try {
2420//                mNetd.createNetwork(thisNetId, thisIface);
2421            } catch (Exception e) {
2422                loge("Exception creating network :" + e);
2423                teardown(thisNet);
2424                return;
2425            }
2426// Already in place in new function. This is dead code.
2427//            setupDataActivityTracking(newNetType);
2428            synchronized (ConnectivityService.this) {
2429                // have a new default network, release the transition wakelock in a second
2430                // if it's held.  The second pause is to allow apps to reconnect over the
2431                // new network
2432                if (mNetTransitionWakeLock.isHeld()) {
2433                    mHandler.sendMessageDelayed(mHandler.obtainMessage(
2434                            EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2435                            mNetTransitionWakeLockSerialNumber, 0),
2436                            1000);
2437                }
2438            }
2439            mActiveDefaultNetwork = newNetType;
2440            try {
2441                mNetd.setDefaultNetId(thisNetId);
2442            } catch (Exception e) {
2443                loge("Exception setting default network :" + e);
2444            }
2445            // this will cause us to come up initially as unconnected and switching
2446            // to connected after our normal pause unless somebody reports us as reall
2447            // disconnected
2448            mDefaultInetConditionPublished = 0;
2449            mDefaultConnectionSequence++;
2450            mInetConditionChangeInFlight = false;
2451            // Don't do this - if we never sign in stay, grey
2452            //reportNetworkCondition(mActiveDefaultNetwork, 100);
2453            updateNetworkSettings(thisNet);
2454        } else {
2455            int thisNetId = nextNetId();
2456            thisNet.setNetId(thisNetId);
2457            try {
2458//                mNetd.createNetwork(thisNetId, thisIface);
2459            } catch (Exception e) {
2460                loge("Exception creating network :" + e);
2461                teardown(thisNet);
2462                return;
2463            }
2464        }
2465        thisNet.setTeardownRequested(false);
2466// Already in place in new function. This is dead code.
2467//        updateMtuSizeSettings(thisNet);
2468//        handleConnectivityChange(newNetType, false);
2469        sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
2470
2471        // notify battery stats service about this network
2472        if (thisIface != null) {
2473            try {
2474                BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
2475            } catch (RemoteException e) {
2476                // ignored; service lives in system_server
2477            }
2478        }
2479    }
2480
2481    /** @hide */
2482    @Override
2483    public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
2484        enforceConnectivityInternalPermission();
2485        if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
2486//        mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
2487    }
2488
2489    /**
2490     * Setup data activity tracking for the given network.
2491     *
2492     * Every {@code setupDataActivityTracking} should be paired with a
2493     * {@link #removeDataActivityTracking} for cleanup.
2494     */
2495    private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
2496        final String iface = networkAgent.linkProperties.getInterfaceName();
2497
2498        final int timeout;
2499        int type = ConnectivityManager.TYPE_NONE;
2500
2501        if (networkAgent.networkCapabilities.hasTransport(
2502                NetworkCapabilities.TRANSPORT_CELLULAR)) {
2503            timeout = Settings.Global.getInt(mContext.getContentResolver(),
2504                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
2505                                             5);
2506            type = ConnectivityManager.TYPE_MOBILE;
2507        } else if (networkAgent.networkCapabilities.hasTransport(
2508                NetworkCapabilities.TRANSPORT_WIFI)) {
2509            timeout = Settings.Global.getInt(mContext.getContentResolver(),
2510                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
2511                                             0);
2512            type = ConnectivityManager.TYPE_WIFI;
2513        } else {
2514            // do not track any other networks
2515            timeout = 0;
2516        }
2517
2518        if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
2519            try {
2520                mNetd.addIdleTimer(iface, timeout, type);
2521            } catch (Exception e) {
2522                // You shall not crash!
2523                loge("Exception in setupDataActivityTracking " + e);
2524            }
2525        }
2526    }
2527
2528    /**
2529     * Remove data activity tracking when network disconnects.
2530     */
2531    private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
2532        final String iface = networkAgent.linkProperties.getInterfaceName();
2533        final NetworkCapabilities caps = networkAgent.networkCapabilities;
2534
2535        if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
2536                              caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
2537            try {
2538                // the call fails silently if no idletimer setup for this interface
2539                mNetd.removeIdleTimer(iface);
2540            } catch (Exception e) {
2541                loge("Exception in removeDataActivityTracking " + e);
2542            }
2543        }
2544    }
2545
2546    /**
2547     * After a change in the connectivity state of a network. We're mainly
2548     * concerned with making sure that the list of DNS servers is set up
2549     * according to which networks are connected, and ensuring that the
2550     * right routing table entries exist.
2551     *
2552     * TODO - delete when we're sure all this functionallity is captured.
2553     */
2554    private void handleConnectivityChange(int netType, LinkProperties curLp, boolean doReset) {
2555        int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2556        boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
2557        if (VDBG) {
2558            log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
2559                    + " resetMask=" + resetMask);
2560        }
2561
2562        /*
2563         * If a non-default network is enabled, add the host routes that
2564         * will allow it's DNS servers to be accessed.
2565         */
2566        handleDnsConfigurationChange(netType);
2567
2568        LinkProperties newLp = null;
2569
2570        if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2571            newLp = mNetTrackers[netType].getLinkProperties();
2572            if (VDBG) {
2573                log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2574                        " doReset=" + doReset + " resetMask=" + resetMask +
2575                        "\n   curLp=" + curLp +
2576                        "\n   newLp=" + newLp);
2577            }
2578
2579            if (curLp != null) {
2580                if (curLp.isIdenticalInterfaceName(newLp)) {
2581                    CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2582                    if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2583                        for (LinkAddress linkAddr : car.removed) {
2584                            if (linkAddr.getAddress() instanceof Inet4Address) {
2585                                resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2586                            }
2587                            if (linkAddr.getAddress() instanceof Inet6Address) {
2588                                resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2589                            }
2590                        }
2591                        if (DBG) {
2592                            log("handleConnectivityChange: addresses changed" +
2593                                    " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2594                                    "\n   car=" + car);
2595                        }
2596                    } else {
2597                        if (VDBG) {
2598                            log("handleConnectivityChange: addresses are the same reset per" +
2599                                   " doReset linkProperty[" + netType + "]:" +
2600                                   " resetMask=" + resetMask);
2601                        }
2602                    }
2603                } else {
2604                    resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
2605                    if (DBG) {
2606                        log("handleConnectivityChange: interface not not equivalent reset both" +
2607                                " linkProperty[" + netType + "]:" +
2608                                " resetMask=" + resetMask);
2609                    }
2610                }
2611            }
2612            if (mNetConfigs[netType].isDefault()) {
2613                handleApplyDefaultProxy(newLp.getHttpProxy());
2614            }
2615        } else {
2616            if (VDBG) {
2617                log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2618                        " doReset=" + doReset + " resetMask=" + resetMask +
2619                        "\n  curLp=" + curLp +
2620                        "\n  newLp= null");
2621            }
2622        }
2623        mCurrentLinkProperties[netType] = newLp;
2624        boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt,
2625                                        mNetTrackers[netType].getNetwork().netId);
2626
2627        if (resetMask != 0 || resetDns) {
2628            if (VDBG) log("handleConnectivityChange: resetting");
2629            if (curLp != null) {
2630                if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
2631                for (String iface : curLp.getAllInterfaceNames()) {
2632                    if (TextUtils.isEmpty(iface) == false) {
2633                        if (resetMask != 0) {
2634                            if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2635                            NetworkUtils.resetConnections(iface, resetMask);
2636
2637                            // Tell VPN the interface is down. It is a temporary
2638                            // but effective fix to make VPN aware of the change.
2639                            if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2640                                synchronized(mVpns) {
2641                                    for (int i = 0; i < mVpns.size(); i++) {
2642                                        mVpns.valueAt(i).interfaceStatusChanged(iface, false);
2643                                    }
2644                                }
2645                            }
2646                        }
2647                    } else {
2648                        loge("Can't reset connection for type "+netType);
2649                    }
2650                }
2651                if (resetDns) {
2652                    flushVmDnsCache();
2653                    if (VDBG) log("resetting DNS cache for type " + netType);
2654                    try {
2655                        mNetd.flushNetworkDnsCache(mNetTrackers[netType].getNetwork().netId);
2656                    } catch (Exception e) {
2657                        // never crash - catch them all
2658                        if (DBG) loge("Exception resetting dns cache: " + e);
2659                    }
2660                }
2661            }
2662        }
2663
2664        // TODO: Temporary notifying upstread change to Tethering.
2665        //       @see bug/4455071
2666        /** Notify TetheringService if interface name has been changed. */
2667        if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
2668                             PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
2669            if (isTetheringSupported()) {
2670                mTethering.handleTetherIfaceChange();
2671            }
2672        }
2673    }
2674
2675    /**
2676     * Add and remove routes using the old properties (null if not previously connected),
2677     * new properties (null if becoming disconnected).  May even be double null, which
2678     * is a noop.
2679     * Uses isLinkDefault to determine if default routes should be set or conversely if
2680     * host routes should be set to the dns servers
2681     * returns a boolean indicating the routes changed
2682     */
2683    private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2684            boolean isLinkDefault, boolean exempt, int netId) {
2685        Collection<RouteInfo> routesToAdd = null;
2686        CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2687        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
2688        if (curLp != null) {
2689            // check for the delta between the current set and the new
2690            routeDiff = curLp.compareAllRoutes(newLp);
2691            dnsDiff = curLp.compareDnses(newLp);
2692        } else if (newLp != null) {
2693            routeDiff.added = newLp.getAllRoutes();
2694            dnsDiff.added = newLp.getDnsServers();
2695        }
2696
2697        boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2698
2699        for (RouteInfo r : routeDiff.removed) {
2700            if (isLinkDefault || ! r.isDefaultRoute()) {
2701                if (VDBG) log("updateRoutes: default remove route r=" + r);
2702                removeRoute(curLp, r, TO_DEFAULT_TABLE, netId);
2703            }
2704            if (isLinkDefault == false) {
2705                // remove from a secondary route table
2706                removeRoute(curLp, r, TO_SECONDARY_TABLE, netId);
2707            }
2708        }
2709
2710        for (RouteInfo r :  routeDiff.added) {
2711            if (isLinkDefault || ! r.isDefaultRoute()) {
2712                addRoute(newLp, r, TO_DEFAULT_TABLE, exempt, netId);
2713            } else {
2714                // add to a secondary route table
2715                addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT, netId);
2716
2717                // many radios add a default route even when we don't want one.
2718                // remove the default route unless somebody else has asked for it
2719                String ifaceName = newLp.getInterfaceName();
2720                synchronized (mRoutesLock) {
2721                    if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
2722                        if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2723                        try {
2724                            mNetd.removeRoute(netId, r);
2725                        } catch (Exception e) {
2726                            // never crash - catch them all
2727                            if (DBG) loge("Exception trying to remove a route: " + e);
2728                        }
2729                    }
2730                }
2731            }
2732        }
2733
2734        return routesChanged;
2735    }
2736
2737    /**
2738     * Reads the network specific MTU size from reources.
2739     * and set it on it's iface.
2740     */
2741    private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2742        final String iface = newLp.getInterfaceName();
2743        final int mtu = newLp.getMtu();
2744        if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2745            if (VDBG) log("identical MTU - not setting");
2746            return;
2747        }
2748
2749        if (mtu < 68 || mtu > 10000) {
2750            loge("Unexpected mtu value: " + mtu + ", " + iface);
2751            return;
2752        }
2753
2754        try {
2755            if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
2756            mNetd.setMtu(iface, mtu);
2757        } catch (Exception e) {
2758            Slog.e(TAG, "exception in setMtu()" + e);
2759        }
2760    }
2761
2762    /**
2763     * Reads the network specific TCP buffer sizes from SystemProperties
2764     * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2765     * wide use
2766     */
2767    private void updateNetworkSettings(NetworkStateTracker nt) {
2768        String key = nt.getTcpBufferSizesPropName();
2769        String bufferSizes = key == null ? null : SystemProperties.get(key);
2770
2771        if (TextUtils.isEmpty(bufferSizes)) {
2772            if (VDBG) log(key + " not found in system properties. Using defaults");
2773
2774            // Setting to default values so we won't be stuck to previous values
2775            key = "net.tcp.buffersize.default";
2776            bufferSizes = SystemProperties.get(key);
2777        }
2778
2779        // Set values in kernel
2780        if (bufferSizes.length() != 0) {
2781            if (VDBG) {
2782                log("Setting TCP values: [" + bufferSizes
2783                        + "] which comes from [" + key + "]");
2784            }
2785            setBufferSize(bufferSizes);
2786        }
2787
2788        final String defaultRwndKey = "net.tcp.default_init_rwnd";
2789        int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
2790        Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
2791            Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
2792        final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
2793        if (rwndValue != 0) {
2794            SystemProperties.set(sysctlKey, rwndValue.toString());
2795        }
2796    }
2797
2798    /**
2799     * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2800     * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2801     *
2802     * @param bufferSizes in the format of "readMin, readInitial, readMax,
2803     *        writeMin, writeInitial, writeMax"
2804     */
2805    private void setBufferSize(String bufferSizes) {
2806        try {
2807            String[] values = bufferSizes.split(",");
2808
2809            if (values.length == 6) {
2810              final String prefix = "/sys/kernel/ipv4/tcp_";
2811                FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2812                FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2813                FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2814                FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2815                FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2816                FileUtils.stringToFile(prefix + "wmem_max", values[5]);
2817            } else {
2818                loge("Invalid buffersize string: " + bufferSizes);
2819            }
2820        } catch (IOException e) {
2821            loge("Can't set tcp buffer sizes:" + e);
2822        }
2823    }
2824
2825    /**
2826     * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2827     * on the highest priority active net which this process requested.
2828     * If there aren't any, clear it out
2829     */
2830    private void reassessPidDns(int pid, boolean doBump)
2831    {
2832        if (VDBG) log("reassessPidDns for pid " + pid);
2833        Integer myPid = new Integer(pid);
2834        for(int i : mPriorityList) {
2835            if (mNetConfigs[i].isDefault()) {
2836                continue;
2837            }
2838            NetworkStateTracker nt = mNetTrackers[i];
2839            if (nt.getNetworkInfo().isConnected() &&
2840                    !nt.isTeardownRequested()) {
2841                LinkProperties p = nt.getLinkProperties();
2842                if (p == null) continue;
2843                if (mNetRequestersPids[i].contains(myPid)) {
2844                    try {
2845                        // TODO: Reimplement this via local variable in bionic.
2846                        // mNetd.setDnsNetworkForPid(nt.getNetwork().netId, pid);
2847                    } catch (Exception e) {
2848                        Slog.e(TAG, "exception reasseses pid dns: " + e);
2849                    }
2850                    return;
2851                }
2852           }
2853        }
2854        // nothing found - delete
2855        try {
2856            // TODO: Reimplement this via local variable in bionic.
2857            // mNetd.clearDnsNetworkForPid(pid);
2858        } catch (Exception e) {
2859            Slog.e(TAG, "exception clear interface from pid: " + e);
2860        }
2861    }
2862
2863    private void flushVmDnsCache() {
2864        /*
2865         * Tell the VMs to toss their DNS caches
2866         */
2867        Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2868        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
2869        /*
2870         * Connectivity events can happen before boot has completed ...
2871         */
2872        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2873        final long ident = Binder.clearCallingIdentity();
2874        try {
2875            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2876        } finally {
2877            Binder.restoreCallingIdentity(ident);
2878        }
2879    }
2880
2881    // Caller must grab mDnsLock.
2882    private void updateDnsLocked(String network, int netId,
2883            Collection<InetAddress> dnses, String domains) {
2884        int last = 0;
2885        if (dnses.size() == 0 && mDefaultDns != null) {
2886            dnses = new ArrayList();
2887            dnses.add(mDefaultDns);
2888            if (DBG) {
2889                loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
2890            }
2891        }
2892
2893        try {
2894            mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), domains);
2895
2896            for (InetAddress dns : dnses) {
2897                ++last;
2898                String key = "net.dns" + last;
2899                String value = dns.getHostAddress();
2900                SystemProperties.set(key, value);
2901            }
2902            for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2903                String key = "net.dns" + i;
2904                SystemProperties.set(key, "");
2905            }
2906            mNumDnsEntries = last;
2907        } catch (Exception e) {
2908            loge("exception setting default dns interface: " + e);
2909        }
2910    }
2911
2912    private void handleDnsConfigurationChange(int netType) {
2913        // add default net's dns entries
2914        NetworkStateTracker nt = mNetTrackers[netType];
2915        if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
2916            LinkProperties p = nt.getLinkProperties();
2917            if (p == null) return;
2918            Collection<InetAddress> dnses = p.getDnsServers();
2919            int netId = nt.getNetwork().netId;
2920            if (mNetConfigs[netType].isDefault()) {
2921                String network = nt.getNetworkInfo().getTypeName();
2922                synchronized (mDnsLock) {
2923                    updateDnsLocked(network, netId, dnses, p.getDomains());
2924                }
2925            } else {
2926                try {
2927                    mNetd.setDnsServersForNetwork(netId,
2928                            NetworkUtils.makeStrings(dnses), p.getDomains());
2929                } catch (Exception e) {
2930                    if (DBG) loge("exception setting dns servers: " + e);
2931                }
2932                // set per-pid dns for attached secondary nets
2933                List<Integer> pids = mNetRequestersPids[netType];
2934                for (Integer pid : pids) {
2935                    try {
2936                        // TODO: Reimplement this via local variable in bionic.
2937                        // mNetd.setDnsNetworkForPid(netId, pid);
2938                    } catch (Exception e) {
2939                        Slog.e(TAG, "exception setting interface for pid: " + e);
2940                    }
2941                }
2942            }
2943            flushVmDnsCache();
2944        }
2945    }
2946
2947    @Override
2948    public int getRestoreDefaultNetworkDelay(int networkType) {
2949        String restoreDefaultNetworkDelayStr = SystemProperties.get(
2950                NETWORK_RESTORE_DELAY_PROP_NAME);
2951        if(restoreDefaultNetworkDelayStr != null &&
2952                restoreDefaultNetworkDelayStr.length() != 0) {
2953            try {
2954                return Integer.valueOf(restoreDefaultNetworkDelayStr);
2955            } catch (NumberFormatException e) {
2956            }
2957        }
2958        // if the system property isn't set, use the value for the apn type
2959        int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2960
2961        if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2962                (mNetConfigs[networkType] != null)) {
2963            ret = mNetConfigs[networkType].restoreTime;
2964        }
2965        return ret;
2966    }
2967
2968    @Override
2969    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2970        final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
2971        if (mContext.checkCallingOrSelfPermission(
2972                android.Manifest.permission.DUMP)
2973                != PackageManager.PERMISSION_GRANTED) {
2974            pw.println("Permission Denial: can't dump ConnectivityService " +
2975                    "from from pid=" + Binder.getCallingPid() + ", uid=" +
2976                    Binder.getCallingUid());
2977            return;
2978        }
2979
2980        pw.println("NetworkFactories for:");
2981        pw.increaseIndent();
2982        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2983            pw.println(nfi.name);
2984        }
2985        pw.decreaseIndent();
2986        pw.println();
2987
2988        NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
2989        pw.print("Active default network: ");
2990        if (defaultNai == null) {
2991            pw.println("none");
2992        } else {
2993            pw.println(defaultNai.network.netId);
2994        }
2995        pw.println();
2996
2997        pw.println("Current Networks:");
2998        pw.increaseIndent();
2999        for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
3000            pw.println(nai.toString());
3001            pw.increaseIndent();
3002            pw.println("Requests:");
3003            pw.increaseIndent();
3004            for (int i = 0; i < nai.networkRequests.size(); i++) {
3005                pw.println(nai.networkRequests.valueAt(i).toString());
3006            }
3007            pw.decreaseIndent();
3008            pw.println("Lingered:");
3009            pw.increaseIndent();
3010            for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
3011            pw.decreaseIndent();
3012            pw.decreaseIndent();
3013        }
3014        pw.decreaseIndent();
3015        pw.println();
3016
3017        pw.println("Network Requests:");
3018        pw.increaseIndent();
3019        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3020            pw.println(nri.toString());
3021        }
3022        pw.println();
3023        pw.decreaseIndent();
3024
3025        synchronized (this) {
3026            pw.println("NetworkTranstionWakeLock is currently " +
3027                    (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
3028            pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
3029        }
3030        pw.println();
3031
3032        mTethering.dump(fd, pw, args);
3033
3034        if (mInetLog != null) {
3035            pw.println();
3036            pw.println("Inet condition reports:");
3037            pw.increaseIndent();
3038            for(int i = 0; i < mInetLog.size(); i++) {
3039                pw.println(mInetLog.get(i));
3040            }
3041            pw.decreaseIndent();
3042        }
3043    }
3044
3045    // must be stateless - things change under us.
3046    private class NetworkStateTrackerHandler extends Handler {
3047        public NetworkStateTrackerHandler(Looper looper) {
3048            super(looper);
3049        }
3050
3051        @Override
3052        public void handleMessage(Message msg) {
3053            NetworkInfo info;
3054            switch (msg.what) {
3055                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
3056                    handleAsyncChannelHalfConnect(msg);
3057                    break;
3058                }
3059                case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
3060                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3061                    if (nai != null) nai.asyncChannel.disconnect();
3062                    break;
3063                }
3064                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
3065                    handleAsyncChannelDisconnected(msg);
3066                    break;
3067                }
3068                case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
3069                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3070                    if (nai == null) {
3071                        loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
3072                    } else {
3073                        updateCapabilities(nai, (NetworkCapabilities)msg.obj);
3074                    }
3075                    break;
3076                }
3077                case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
3078                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3079                    if (nai == null) {
3080                        loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
3081                    } else {
3082                        if (VDBG) log("Update of Linkproperties for " + nai.name());
3083                        LinkProperties oldLp = nai.linkProperties;
3084                        nai.linkProperties = (LinkProperties)msg.obj;
3085                        updateLinkProperties(nai, oldLp);
3086                    }
3087                    break;
3088                }
3089                case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
3090                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3091                    if (nai == null) {
3092                        loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
3093                        break;
3094                    }
3095                    info = (NetworkInfo) msg.obj;
3096                    updateNetworkInfo(nai, info);
3097                    break;
3098                }
3099                case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
3100                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3101                    if (nai == null) {
3102                        loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
3103                        break;
3104                    }
3105                    Integer score = (Integer) msg.obj;
3106                    if (score != null) updateNetworkScore(nai, score.intValue());
3107                    break;
3108                }
3109                case NetworkMonitor.EVENT_NETWORK_VALIDATED: {
3110                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
3111                    handleConnectionValidated(nai);
3112                    break;
3113                }
3114                case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
3115                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
3116                    handleLingerComplete(nai);
3117                    break;
3118                }
3119                case NetworkStateTracker.EVENT_STATE_CHANGED: {
3120                    info = (NetworkInfo) msg.obj;
3121                    NetworkInfo.State state = info.getState();
3122
3123                    if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
3124                            (state == NetworkInfo.State.DISCONNECTED) ||
3125                            (state == NetworkInfo.State.SUSPENDED)) {
3126                        log("ConnectivityChange for " +
3127                            info.getTypeName() + ": " +
3128                            state + "/" + info.getDetailedState());
3129                    }
3130
3131                    // Since mobile has the notion of a network/apn that can be used for
3132                    // provisioning we need to check every time we're connected as
3133                    // CaptiveProtalTracker won't detected it because DCT doesn't report it
3134                    // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
3135                    // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
3136                    // is received by MDST and sent here as EVENT_STATE_CHANGED.
3137                    if (ConnectivityManager.isNetworkTypeMobile(info.getType())
3138                            && (0 != Settings.Global.getInt(mContext.getContentResolver(),
3139                                        Settings.Global.DEVICE_PROVISIONED, 0))
3140                            && (((state == NetworkInfo.State.CONNECTED)
3141                                    && (info.getType() == ConnectivityManager.TYPE_MOBILE))
3142                                || info.isConnectedToProvisioningNetwork())) {
3143                        log("ConnectivityChange checkMobileProvisioning for"
3144                                + " TYPE_MOBILE or ProvisioningNetwork");
3145                        checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
3146                    }
3147
3148                    EventLogTags.writeConnectivityStateChanged(
3149                            info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
3150
3151                    if (info.isConnectedToProvisioningNetwork()) {
3152                        /**
3153                         * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
3154                         * for now its an in between network, its a network that
3155                         * is actually a default network but we don't want it to be
3156                         * announced as such to keep background applications from
3157                         * trying to use it. It turns out that some still try so we
3158                         * take the additional step of clearing any default routes
3159                         * to the link that may have incorrectly setup by the lower
3160                         * levels.
3161                         */
3162                        LinkProperties lp = getLinkPropertiesForTypeInternal(info.getType());
3163                        if (DBG) {
3164                            log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
3165                        }
3166
3167                        // Clear any default routes setup by the radio so
3168                        // any activity by applications trying to use this
3169                        // connection will fail until the provisioning network
3170                        // is enabled.
3171                        for (RouteInfo r : lp.getRoutes()) {
3172                            removeRoute(lp, r, TO_DEFAULT_TABLE,
3173                                        mNetTrackers[info.getType()].getNetwork().netId);
3174                        }
3175                    } else if (state == NetworkInfo.State.DISCONNECTED) {
3176                    } else if (state == NetworkInfo.State.SUSPENDED) {
3177                    } else if (state == NetworkInfo.State.CONNECTED) {
3178                    //    handleConnect(info);
3179                    }
3180                    if (mLockdownTracker != null) {
3181                        mLockdownTracker.onNetworkInfoChanged(info);
3182                    }
3183                    break;
3184                }
3185                case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
3186                    info = (NetworkInfo) msg.obj;
3187                    // TODO: Temporary allowing network configuration
3188                    //       change not resetting sockets.
3189                    //       @see bug/4455071
3190                    handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()],
3191                            false);
3192                    break;
3193                }
3194                case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
3195                    info = (NetworkInfo) msg.obj;
3196                    int type = info.getType();
3197                    if (mNetConfigs[type].isDefault()) updateNetworkSettings(mNetTrackers[type]);
3198                    break;
3199                }
3200            }
3201        }
3202    }
3203
3204    private void handleAsyncChannelHalfConnect(Message msg) {
3205        AsyncChannel ac = (AsyncChannel) msg.obj;
3206        if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
3207            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
3208                if (VDBG) log("NetworkFactory connected");
3209                // A network factory has connected.  Send it all current NetworkRequests.
3210                for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3211                    if (nri.isRequest == false) continue;
3212                    NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
3213                    ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
3214                            (nai != null ? nai.currentScore : 0), 0, nri.request);
3215                }
3216            } else {
3217                loge("Error connecting NetworkFactory");
3218                mNetworkFactoryInfos.remove(msg.obj);
3219            }
3220        } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
3221            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
3222                if (VDBG) log("NetworkAgent connected");
3223                // A network agent has requested a connection.  Establish the connection.
3224                mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
3225                        sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
3226            } else {
3227                loge("Error connecting NetworkAgent");
3228                NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
3229                if (nai != null) {
3230                    mNetworkForNetId.remove(nai.network.netId);
3231                    mLegacyTypeTracker.remove(nai);
3232                }
3233            }
3234        }
3235    }
3236    private void handleAsyncChannelDisconnected(Message msg) {
3237        NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
3238        if (nai != null) {
3239            if (DBG) {
3240                log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
3241            }
3242            // A network agent has disconnected.
3243            // Tell netd to clean up the configuration for this network
3244            // (routing rules, DNS, etc).
3245            try {
3246                mNetd.removeNetwork(nai.network.netId);
3247            } catch (Exception e) {
3248                loge("Exception removing network: " + e);
3249            }
3250            // TODO - if we move the logic to the network agent (have them disconnect
3251            // because they lost all their requests or because their score isn't good)
3252            // then they would disconnect organically, report their new state and then
3253            // disconnect the channel.
3254            if (nai.networkInfo.isConnected()) {
3255                nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3256                        null, null);
3257            }
3258            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
3259            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
3260            mNetworkAgentInfos.remove(msg.replyTo);
3261            updateClat(null, nai.linkProperties, nai);
3262            mLegacyTypeTracker.remove(nai);
3263            mNetworkForNetId.remove(nai.network.netId);
3264            // Since we've lost the network, go through all the requests that
3265            // it was satisfying and see if any other factory can satisfy them.
3266            final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
3267            for (int i = 0; i < nai.networkRequests.size(); i++) {
3268                NetworkRequest request = nai.networkRequests.valueAt(i);
3269                NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
3270                if (VDBG) {
3271                    log(" checking request " + request + ", currentNetwork = " +
3272                            (currentNetwork != null ? currentNetwork.name() : "null"));
3273                }
3274                if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
3275                    mNetworkForRequestId.remove(request.requestId);
3276                    sendUpdatedScoreToFactories(request, 0);
3277                    NetworkAgentInfo alternative = null;
3278                    for (Map.Entry entry : mNetworkAgentInfos.entrySet()) {
3279                        NetworkAgentInfo existing = (NetworkAgentInfo)entry.getValue();
3280                        if (existing.networkInfo.isConnected() &&
3281                                request.networkCapabilities.satisfiedByNetworkCapabilities(
3282                                existing.networkCapabilities) &&
3283                                (alternative == null ||
3284                                 alternative.currentScore < existing.currentScore)) {
3285                            alternative = existing;
3286                        }
3287                    }
3288                    if (alternative != null && !toActivate.contains(alternative)) {
3289                        toActivate.add(alternative);
3290                    }
3291                }
3292            }
3293            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
3294                removeDataActivityTracking(nai);
3295                mActiveDefaultNetwork = ConnectivityManager.TYPE_NONE;
3296            }
3297            for (NetworkAgentInfo networkToActivate : toActivate) {
3298                networkToActivate.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
3299            }
3300        }
3301    }
3302
3303    private void handleRegisterNetworkRequest(Message msg) {
3304        final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3305        final NetworkCapabilities newCap = nri.request.networkCapabilities;
3306        int score = 0;
3307
3308        // Check for the best currently alive network that satisfies this request
3309        NetworkAgentInfo bestNetwork = null;
3310        for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
3311            if (VDBG) log("handleRegisterNetworkRequest checking " + network.name());
3312            if (newCap.satisfiedByNetworkCapabilities(network.networkCapabilities)) {
3313                if (VDBG) log("apparently satisfied.  currentScore=" + network.currentScore);
3314                if ((bestNetwork == null) || bestNetwork.currentScore < network.currentScore) {
3315                    bestNetwork = network;
3316                }
3317            }
3318        }
3319        if (bestNetwork != null) {
3320            if (VDBG) log("using " + bestNetwork.name());
3321            bestNetwork.addRequest(nri.request);
3322            mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
3323            int legacyType = nri.request.legacyType;
3324            if (legacyType != TYPE_NONE) {
3325                mLegacyTypeTracker.add(legacyType, bestNetwork);
3326            }
3327            notifyNetworkCallback(bestNetwork, nri);
3328            score = bestNetwork.currentScore;
3329        }
3330        mNetworkRequests.put(nri.request, nri);
3331        if (msg.what == EVENT_REGISTER_NETWORK_REQUEST) {
3332            if (DBG) log("sending new NetworkRequest to factories");
3333            for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3334                nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
3335                        0, nri.request);
3336            }
3337        }
3338    }
3339
3340    private void handleReleaseNetworkRequest(NetworkRequest request) {
3341        if (DBG) log("releasing NetworkRequest " + request);
3342        NetworkRequestInfo nri = mNetworkRequests.remove(request);
3343        if (nri != null) {
3344            // tell the network currently servicing this that it's no longer interested
3345            NetworkAgentInfo affectedNetwork = mNetworkForRequestId.get(nri.request.requestId);
3346            if (affectedNetwork != null) {
3347                mNetworkForRequestId.remove(nri.request.requestId);
3348                affectedNetwork.networkRequests.remove(nri.request.requestId);
3349                if (VDBG) {
3350                    log(" Removing from current network " + affectedNetwork.name() + ", leaving " +
3351                            affectedNetwork.networkRequests.size() + " requests.");
3352                }
3353            }
3354
3355            if (nri.isRequest) {
3356                for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3357                    nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
3358                            nri.request);
3359                }
3360
3361                if (affectedNetwork != null) {
3362                    // check if this network still has live requests - otherwise, tear down
3363                    // TODO - probably push this to the NF/NA
3364                    boolean keep = false;
3365                    for (int i = 0; i < affectedNetwork.networkRequests.size(); i++) {
3366                        NetworkRequest r = affectedNetwork.networkRequests.valueAt(i);
3367                        if (mNetworkRequests.get(r).isRequest) {
3368                            keep = true;
3369                            break;
3370                        }
3371                    }
3372                    if (keep == false) {
3373                        if (DBG) log("no live requests for " + affectedNetwork.name() +
3374                                "; disconnecting");
3375                        affectedNetwork.asyncChannel.disconnect();
3376                    }
3377                }
3378            }
3379            callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
3380        }
3381    }
3382
3383    private class InternalHandler extends Handler {
3384        public InternalHandler(Looper looper) {
3385            super(looper);
3386        }
3387
3388        @Override
3389        public void handleMessage(Message msg) {
3390            NetworkInfo info;
3391            switch (msg.what) {
3392                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
3393                    String causedBy = null;
3394                    synchronized (ConnectivityService.this) {
3395                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
3396                                mNetTransitionWakeLock.isHeld()) {
3397                            mNetTransitionWakeLock.release();
3398                            causedBy = mNetTransitionWakeLockCausedBy;
3399                        }
3400                    }
3401                    if (causedBy != null) {
3402                        log("NetTransition Wakelock for " + causedBy + " released by timeout");
3403                    }
3404                    break;
3405                }
3406                case EVENT_RESTORE_DEFAULT_NETWORK: {
3407                    FeatureUser u = (FeatureUser)msg.obj;
3408                    u.expire();
3409                    break;
3410                }
3411                case EVENT_INET_CONDITION_CHANGE: {
3412                    int netType = msg.arg1;
3413                    int condition = msg.arg2;
3414                    handleInetConditionChange(netType, condition);
3415                    break;
3416                }
3417                case EVENT_INET_CONDITION_HOLD_END: {
3418                    int netType = msg.arg1;
3419                    int sequence = msg.arg2;
3420                    handleInetConditionHoldEnd(netType, sequence);
3421                    break;
3422                }
3423                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
3424                    handleDeprecatedGlobalHttpProxy();
3425                    break;
3426                }
3427                case EVENT_SET_DEPENDENCY_MET: {
3428                    boolean met = (msg.arg1 == ENABLED);
3429                    handleSetDependencyMet(msg.arg2, met);
3430                    break;
3431                }
3432                case EVENT_SEND_STICKY_BROADCAST_INTENT: {
3433                    Intent intent = (Intent)msg.obj;
3434                    sendStickyBroadcast(intent);
3435                    break;
3436                }
3437                case EVENT_SET_POLICY_DATA_ENABLE: {
3438                    final int networkType = msg.arg1;
3439                    final boolean enabled = msg.arg2 == ENABLED;
3440                    handleSetPolicyDataEnable(networkType, enabled);
3441                    break;
3442                }
3443                case EVENT_VPN_STATE_CHANGED: {
3444                    if (mLockdownTracker != null) {
3445                        mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
3446                    }
3447                    break;
3448                }
3449                case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
3450                    int tag = mEnableFailFastMobileDataTag.get();
3451                    if (msg.arg1 == tag) {
3452                        MobileDataStateTracker mobileDst =
3453                            (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
3454                        if (mobileDst != null) {
3455                            mobileDst.setEnableFailFastMobileData(msg.arg2);
3456                        }
3457                    } else {
3458                        log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
3459                                + " != tag:" + tag);
3460                    }
3461                    break;
3462                }
3463                case EVENT_SAMPLE_INTERVAL_ELAPSED: {
3464                    handleNetworkSamplingTimeout();
3465                    break;
3466                }
3467                case EVENT_PROXY_HAS_CHANGED: {
3468                    handleApplyDefaultProxy((ProxyInfo)msg.obj);
3469                    break;
3470                }
3471                case EVENT_REGISTER_NETWORK_FACTORY: {
3472                    handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
3473                    break;
3474                }
3475                case EVENT_UNREGISTER_NETWORK_FACTORY: {
3476                    handleUnregisterNetworkFactory((Messenger)msg.obj);
3477                    break;
3478                }
3479                case EVENT_REGISTER_NETWORK_AGENT: {
3480                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
3481                    break;
3482                }
3483                case EVENT_REGISTER_NETWORK_REQUEST:
3484                case EVENT_REGISTER_NETWORK_LISTENER: {
3485                    handleRegisterNetworkRequest(msg);
3486                    break;
3487                }
3488                case EVENT_RELEASE_NETWORK_REQUEST: {
3489                    handleReleaseNetworkRequest((NetworkRequest) msg.obj);
3490                    break;
3491                }
3492            }
3493        }
3494    }
3495
3496    // javadoc from interface
3497    public int tether(String iface) {
3498        enforceTetherChangePermission();
3499
3500        if (isTetheringSupported()) {
3501            return mTethering.tether(iface);
3502        } else {
3503            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3504        }
3505    }
3506
3507    // javadoc from interface
3508    public int untether(String iface) {
3509        enforceTetherChangePermission();
3510
3511        if (isTetheringSupported()) {
3512            return mTethering.untether(iface);
3513        } else {
3514            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3515        }
3516    }
3517
3518    // javadoc from interface
3519    public int getLastTetherError(String iface) {
3520        enforceTetherAccessPermission();
3521
3522        if (isTetheringSupported()) {
3523            return mTethering.getLastTetherError(iface);
3524        } else {
3525            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3526        }
3527    }
3528
3529    // TODO - proper iface API for selection by property, inspection, etc
3530    public String[] getTetherableUsbRegexs() {
3531        enforceTetherAccessPermission();
3532        if (isTetheringSupported()) {
3533            return mTethering.getTetherableUsbRegexs();
3534        } else {
3535            return new String[0];
3536        }
3537    }
3538
3539    public String[] getTetherableWifiRegexs() {
3540        enforceTetherAccessPermission();
3541        if (isTetheringSupported()) {
3542            return mTethering.getTetherableWifiRegexs();
3543        } else {
3544            return new String[0];
3545        }
3546    }
3547
3548    public String[] getTetherableBluetoothRegexs() {
3549        enforceTetherAccessPermission();
3550        if (isTetheringSupported()) {
3551            return mTethering.getTetherableBluetoothRegexs();
3552        } else {
3553            return new String[0];
3554        }
3555    }
3556
3557    public int setUsbTethering(boolean enable) {
3558        enforceTetherChangePermission();
3559        if (isTetheringSupported()) {
3560            return mTethering.setUsbTethering(enable);
3561        } else {
3562            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3563        }
3564    }
3565
3566    // TODO - move iface listing, queries, etc to new module
3567    // javadoc from interface
3568    public String[] getTetherableIfaces() {
3569        enforceTetherAccessPermission();
3570        return mTethering.getTetherableIfaces();
3571    }
3572
3573    public String[] getTetheredIfaces() {
3574        enforceTetherAccessPermission();
3575        return mTethering.getTetheredIfaces();
3576    }
3577
3578    public String[] getTetheringErroredIfaces() {
3579        enforceTetherAccessPermission();
3580        return mTethering.getErroredIfaces();
3581    }
3582
3583    // if ro.tether.denied = true we default to no tethering
3584    // gservices could set the secure setting to 1 though to enable it on a build where it
3585    // had previously been turned off.
3586    public boolean isTetheringSupported() {
3587        enforceTetherAccessPermission();
3588        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
3589        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
3590                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
3591        return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
3592                mTethering.getTetherableWifiRegexs().length != 0 ||
3593                mTethering.getTetherableBluetoothRegexs().length != 0) &&
3594                mTethering.getUpstreamIfaceTypes().length != 0);
3595    }
3596
3597    // An API NetworkStateTrackers can call when they lose their network.
3598    // This will automatically be cleared after X seconds or a network becomes CONNECTED,
3599    // whichever happens first.  The timer is started by the first caller and not
3600    // restarted by subsequent callers.
3601    public void requestNetworkTransitionWakelock(String forWhom) {
3602        enforceConnectivityInternalPermission();
3603        synchronized (this) {
3604            if (mNetTransitionWakeLock.isHeld()) return;
3605            mNetTransitionWakeLockSerialNumber++;
3606            mNetTransitionWakeLock.acquire();
3607            mNetTransitionWakeLockCausedBy = forWhom;
3608        }
3609        mHandler.sendMessageDelayed(mHandler.obtainMessage(
3610                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
3611                mNetTransitionWakeLockSerialNumber, 0),
3612                mNetTransitionWakeLockTimeout);
3613        return;
3614    }
3615
3616    // 100 percent is full good, 0 is full bad.
3617    public void reportInetCondition(int networkType, int percentage) {
3618        if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
3619        mContext.enforceCallingOrSelfPermission(
3620                android.Manifest.permission.STATUS_BAR,
3621                "ConnectivityService");
3622
3623        if (DBG) {
3624            int pid = getCallingPid();
3625            int uid = getCallingUid();
3626            String s = pid + "(" + uid + ") reports inet is " +
3627                (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
3628                "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
3629            mInetLog.add(s);
3630            while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
3631                mInetLog.remove(0);
3632            }
3633        }
3634        mHandler.sendMessage(mHandler.obtainMessage(
3635            EVENT_INET_CONDITION_CHANGE, networkType, percentage));
3636    }
3637
3638    public void reportBadNetwork(Network network) {
3639        //TODO
3640    }
3641
3642    private void handleInetConditionChange(int netType, int condition) {
3643        if (mActiveDefaultNetwork == -1) {
3644            if (DBG) log("handleInetConditionChange: no active default network - ignore");
3645            return;
3646        }
3647        if (mActiveDefaultNetwork != netType) {
3648            if (DBG) log("handleInetConditionChange: net=" + netType +
3649                            " != default=" + mActiveDefaultNetwork + " - ignore");
3650            return;
3651        }
3652        if (VDBG) {
3653            log("handleInetConditionChange: net=" +
3654                    netType + ", condition=" + condition +
3655                    ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
3656        }
3657        mDefaultInetCondition = condition;
3658        int delay;
3659        if (mInetConditionChangeInFlight == false) {
3660            if (VDBG) log("handleInetConditionChange: starting a change hold");
3661            // setup a new hold to debounce this
3662            if (mDefaultInetCondition > 50) {
3663                delay = Settings.Global.getInt(mContext.getContentResolver(),
3664                        Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
3665            } else {
3666                delay = Settings.Global.getInt(mContext.getContentResolver(),
3667                        Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
3668            }
3669            mInetConditionChangeInFlight = true;
3670            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
3671                    mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
3672        } else {
3673            // we've set the new condition, when this hold ends that will get picked up
3674            if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
3675        }
3676    }
3677
3678    private void handleInetConditionHoldEnd(int netType, int sequence) {
3679        if (DBG) {
3680            log("handleInetConditionHoldEnd: net=" + netType +
3681                    ", condition=" + mDefaultInetCondition +
3682                    ", published condition=" + mDefaultInetConditionPublished);
3683        }
3684        mInetConditionChangeInFlight = false;
3685
3686        if (mActiveDefaultNetwork == -1) {
3687            if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
3688            return;
3689        }
3690        if (mDefaultConnectionSequence != sequence) {
3691            if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
3692            return;
3693        }
3694        // TODO: Figure out why this optimization sometimes causes a
3695        //       change in mDefaultInetCondition to be missed and the
3696        //       UI to not be updated.
3697        //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3698        //    if (DBG) log("no change in condition - aborting");
3699        //    return;
3700        //}
3701        NetworkInfo networkInfo = getNetworkInfoForType(mActiveDefaultNetwork);
3702        if (networkInfo.isConnected() == false) {
3703            if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
3704            return;
3705        }
3706        mDefaultInetConditionPublished = mDefaultInetCondition;
3707        sendInetConditionBroadcast(networkInfo);
3708        return;
3709    }
3710
3711    public ProxyInfo getProxy() {
3712        // this information is already available as a world read/writable jvm property
3713        // so this API change wouldn't have a benifit.  It also breaks the passing
3714        // of proxy info to all the JVMs.
3715        // enforceAccessPermission();
3716        synchronized (mProxyLock) {
3717            ProxyInfo ret = mGlobalProxy;
3718            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3719            return ret;
3720        }
3721    }
3722
3723    public void setGlobalProxy(ProxyInfo proxyProperties) {
3724        enforceConnectivityInternalPermission();
3725
3726        synchronized (mProxyLock) {
3727            if (proxyProperties == mGlobalProxy) return;
3728            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3729            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3730
3731            String host = "";
3732            int port = 0;
3733            String exclList = "";
3734            String pacFileUrl = "";
3735            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
3736                    (proxyProperties.getPacFileUrl() != null))) {
3737                if (!proxyProperties.isValid()) {
3738                    if (DBG)
3739                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3740                    return;
3741                }
3742                mGlobalProxy = new ProxyInfo(proxyProperties);
3743                host = mGlobalProxy.getHost();
3744                port = mGlobalProxy.getPort();
3745                exclList = mGlobalProxy.getExclusionListAsString();
3746                if (proxyProperties.getPacFileUrl() != null) {
3747                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
3748                }
3749            } else {
3750                mGlobalProxy = null;
3751            }
3752            ContentResolver res = mContext.getContentResolver();
3753            final long token = Binder.clearCallingIdentity();
3754            try {
3755                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3756                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3757                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3758                        exclList);
3759                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
3760            } finally {
3761                Binder.restoreCallingIdentity(token);
3762            }
3763        }
3764
3765        if (mGlobalProxy == null) {
3766            proxyProperties = mDefaultProxy;
3767        }
3768        sendProxyBroadcast(proxyProperties);
3769    }
3770
3771    private void loadGlobalProxy() {
3772        ContentResolver res = mContext.getContentResolver();
3773        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3774        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3775        String exclList = Settings.Global.getString(res,
3776                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3777        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3778        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3779            ProxyInfo proxyProperties;
3780            if (!TextUtils.isEmpty(pacFileUrl)) {
3781                proxyProperties = new ProxyInfo(pacFileUrl);
3782            } else {
3783                proxyProperties = new ProxyInfo(host, port, exclList);
3784            }
3785            if (!proxyProperties.isValid()) {
3786                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3787                return;
3788            }
3789
3790            synchronized (mProxyLock) {
3791                mGlobalProxy = proxyProperties;
3792            }
3793        }
3794    }
3795
3796    public ProxyInfo getGlobalProxy() {
3797        // this information is already available as a world read/writable jvm property
3798        // so this API change wouldn't have a benifit.  It also breaks the passing
3799        // of proxy info to all the JVMs.
3800        // enforceAccessPermission();
3801        synchronized (mProxyLock) {
3802            return mGlobalProxy;
3803        }
3804    }
3805
3806    private void handleApplyDefaultProxy(ProxyInfo proxy) {
3807        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3808                && (proxy.getPacFileUrl() == null)) {
3809            proxy = null;
3810        }
3811        synchronized (mProxyLock) {
3812            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3813            if (mDefaultProxy == proxy) return; // catches repeated nulls
3814            if (proxy != null &&  !proxy.isValid()) {
3815                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3816                return;
3817            }
3818
3819            // This call could be coming from the PacManager, containing the port of the local
3820            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
3821            // global (to get the correct local port), and send a broadcast.
3822            // TODO: Switch PacManager to have its own message to send back rather than
3823            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
3824            if ((mGlobalProxy != null) && (proxy != null) && (proxy.getPacFileUrl() != null)
3825                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3826                mGlobalProxy = proxy;
3827                sendProxyBroadcast(mGlobalProxy);
3828                return;
3829            }
3830            mDefaultProxy = proxy;
3831
3832            if (mGlobalProxy != null) return;
3833            if (!mDefaultProxyDisabled) {
3834                sendProxyBroadcast(proxy);
3835            }
3836        }
3837    }
3838
3839    private void handleDeprecatedGlobalHttpProxy() {
3840        String proxy = Settings.Global.getString(mContext.getContentResolver(),
3841                Settings.Global.HTTP_PROXY);
3842        if (!TextUtils.isEmpty(proxy)) {
3843            String data[] = proxy.split(":");
3844            if (data.length == 0) {
3845                return;
3846            }
3847
3848            String proxyHost =  data[0];
3849            int proxyPort = 8080;
3850            if (data.length > 1) {
3851                try {
3852                    proxyPort = Integer.parseInt(data[1]);
3853                } catch (NumberFormatException e) {
3854                    return;
3855                }
3856            }
3857            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
3858            setGlobalProxy(p);
3859        }
3860    }
3861
3862    private void sendProxyBroadcast(ProxyInfo proxy) {
3863        if (proxy == null) proxy = new ProxyInfo("", 0, "");
3864        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
3865        if (DBG) log("sending Proxy Broadcast for " + proxy);
3866        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3867        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3868            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3869        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3870        final long ident = Binder.clearCallingIdentity();
3871        try {
3872            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3873        } finally {
3874            Binder.restoreCallingIdentity(ident);
3875        }
3876    }
3877
3878    private static class SettingsObserver extends ContentObserver {
3879        private int mWhat;
3880        private Handler mHandler;
3881        SettingsObserver(Handler handler, int what) {
3882            super(handler);
3883            mHandler = handler;
3884            mWhat = what;
3885        }
3886
3887        void observe(Context context) {
3888            ContentResolver resolver = context.getContentResolver();
3889            resolver.registerContentObserver(Settings.Global.getUriFor(
3890                    Settings.Global.HTTP_PROXY), false, this);
3891        }
3892
3893        @Override
3894        public void onChange(boolean selfChange) {
3895            mHandler.obtainMessage(mWhat).sendToTarget();
3896        }
3897    }
3898
3899    private static void log(String s) {
3900        Slog.d(TAG, s);
3901    }
3902
3903    private static void loge(String s) {
3904        Slog.e(TAG, s);
3905    }
3906
3907    int convertFeatureToNetworkType(int networkType, String feature) {
3908        int usedNetworkType = networkType;
3909
3910        if(networkType == ConnectivityManager.TYPE_MOBILE) {
3911            if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3912                usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3913            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3914                usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3915            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3916                    TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3917                usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3918            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3919                usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3920            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3921                usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3922            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3923                usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3924            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3925                usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3926            } else {
3927                Slog.e(TAG, "Can't match any mobile netTracker!");
3928            }
3929        } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3930            if (TextUtils.equals(feature, "p2p")) {
3931                usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3932            } else {
3933                Slog.e(TAG, "Can't match any wifi netTracker!");
3934            }
3935        } else {
3936            Slog.e(TAG, "Unexpected network type");
3937        }
3938        return usedNetworkType;
3939    }
3940
3941    private static <T> T checkNotNull(T value, String message) {
3942        if (value == null) {
3943            throw new NullPointerException(message);
3944        }
3945        return value;
3946    }
3947
3948    /**
3949     * Protect a socket from VPN routing rules. This method is used by
3950     * VpnBuilder and not available in ConnectivityManager. Permissions
3951     * are checked in Vpn class.
3952     * @hide
3953     */
3954    @Override
3955    public boolean protectVpn(ParcelFileDescriptor socket) {
3956        throwIfLockdownEnabled();
3957        try {
3958            int type = mActiveDefaultNetwork;
3959            int user = UserHandle.getUserId(Binder.getCallingUid());
3960            if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
3961                synchronized(mVpns) {
3962                    mVpns.get(user).protect(socket);
3963                }
3964                return true;
3965            }
3966        } catch (Exception e) {
3967            // ignore
3968        } finally {
3969            try {
3970                socket.close();
3971            } catch (Exception e) {
3972                // ignore
3973            }
3974        }
3975        return false;
3976    }
3977
3978    /**
3979     * Prepare for a VPN application. This method is used by VpnDialogs
3980     * and not available in ConnectivityManager. Permissions are checked
3981     * in Vpn class.
3982     * @hide
3983     */
3984    @Override
3985    public boolean prepareVpn(String oldPackage, String newPackage) {
3986        throwIfLockdownEnabled();
3987        int user = UserHandle.getUserId(Binder.getCallingUid());
3988        synchronized(mVpns) {
3989            return mVpns.get(user).prepare(oldPackage, newPackage);
3990        }
3991    }
3992
3993    @Override
3994    public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
3995        enforceMarkNetworkSocketPermission();
3996        final long token = Binder.clearCallingIdentity();
3997        try {
3998            int mark = mNetd.getMarkForUid(uid);
3999            // Clear the mark on the socket if no mark is needed to prevent socket reuse issues
4000            if (mark == -1) {
4001                mark = 0;
4002            }
4003            NetworkUtils.markSocket(socket.getFd(), mark);
4004        } catch (RemoteException e) {
4005        } finally {
4006            Binder.restoreCallingIdentity(token);
4007        }
4008    }
4009
4010    /**
4011     * Configure a TUN interface and return its file descriptor. Parameters
4012     * are encoded and opaque to this class. This method is used by VpnBuilder
4013     * and not available in ConnectivityManager. Permissions are checked in
4014     * Vpn class.
4015     * @hide
4016     */
4017    @Override
4018    public ParcelFileDescriptor establishVpn(VpnConfig config) {
4019        throwIfLockdownEnabled();
4020        int user = UserHandle.getUserId(Binder.getCallingUid());
4021        synchronized(mVpns) {
4022            return mVpns.get(user).establish(config);
4023        }
4024    }
4025
4026    /**
4027     * Start legacy VPN, controlling native daemons as needed. Creates a
4028     * secondary thread to perform connection work, returning quickly.
4029     */
4030    @Override
4031    public void startLegacyVpn(VpnProfile profile) {
4032        throwIfLockdownEnabled();
4033        final LinkProperties egress = getActiveLinkProperties();
4034        if (egress == null) {
4035            throw new IllegalStateException("Missing active network connection");
4036        }
4037        int user = UserHandle.getUserId(Binder.getCallingUid());
4038        synchronized(mVpns) {
4039            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
4040        }
4041    }
4042
4043    /**
4044     * Return the information of the ongoing legacy VPN. This method is used
4045     * by VpnSettings and not available in ConnectivityManager. Permissions
4046     * are checked in Vpn class.
4047     * @hide
4048     */
4049    @Override
4050    public LegacyVpnInfo getLegacyVpnInfo() {
4051        throwIfLockdownEnabled();
4052        int user = UserHandle.getUserId(Binder.getCallingUid());
4053        synchronized(mVpns) {
4054            return mVpns.get(user).getLegacyVpnInfo();
4055        }
4056    }
4057
4058    /**
4059     * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
4060     * not available in ConnectivityManager.
4061     * Permissions are checked in Vpn class.
4062     * @hide
4063     */
4064    @Override
4065    public VpnConfig getVpnConfig() {
4066        int user = UserHandle.getUserId(Binder.getCallingUid());
4067        synchronized(mVpns) {
4068            return mVpns.get(user).getVpnConfig();
4069        }
4070    }
4071
4072    /**
4073     * Callback for VPN subsystem. Currently VPN is not adapted to the service
4074     * through NetworkStateTracker since it works differently. For example, it
4075     * needs to override DNS servers but never takes the default routes. It
4076     * relies on another data network, and it could keep existing connections
4077     * alive after reconnecting, switching between networks, or even resuming
4078     * from deep sleep. Calls from applications should be done synchronously
4079     * to avoid race conditions. As these are all hidden APIs, refactoring can
4080     * be done whenever a better abstraction is developed.
4081     */
4082    public class VpnCallback {
4083        private VpnCallback() {
4084        }
4085
4086        public void onStateChanged(NetworkInfo info) {
4087            mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
4088        }
4089
4090        public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
4091            if (dnsServers == null) {
4092                restore();
4093                return;
4094            }
4095
4096            // Convert DNS servers into addresses.
4097            List<InetAddress> addresses = new ArrayList<InetAddress>();
4098            for (String address : dnsServers) {
4099                // Double check the addresses and remove invalid ones.
4100                try {
4101                    addresses.add(InetAddress.parseNumericAddress(address));
4102                } catch (Exception e) {
4103                    // ignore
4104                }
4105            }
4106            if (addresses.isEmpty()) {
4107                restore();
4108                return;
4109            }
4110
4111            // Concatenate search domains into a string.
4112            StringBuilder buffer = new StringBuilder();
4113            if (searchDomains != null) {
4114                for (String domain : searchDomains) {
4115                    buffer.append(domain).append(' ');
4116                }
4117            }
4118            String domains = buffer.toString().trim();
4119
4120            // Apply DNS changes.
4121            synchronized (mDnsLock) {
4122                // TODO: Re-enable this when the netId of the VPN is known.
4123                // updateDnsLocked("VPN", netId, addresses, domains);
4124            }
4125
4126            // Temporarily disable the default proxy (not global).
4127            synchronized (mProxyLock) {
4128                mDefaultProxyDisabled = true;
4129                if (mGlobalProxy == null && mDefaultProxy != null) {
4130                    sendProxyBroadcast(null);
4131                }
4132            }
4133
4134            // TODO: support proxy per network.
4135        }
4136
4137        public void restore() {
4138            synchronized (mProxyLock) {
4139                mDefaultProxyDisabled = false;
4140                if (mGlobalProxy == null && mDefaultProxy != null) {
4141                    sendProxyBroadcast(mDefaultProxy);
4142                }
4143            }
4144        }
4145
4146        public void protect(ParcelFileDescriptor socket) {
4147            try {
4148                final int mark = mNetd.getMarkForProtect();
4149                NetworkUtils.markSocket(socket.getFd(), mark);
4150            } catch (RemoteException e) {
4151            }
4152        }
4153
4154        public void setRoutes(String interfaze, List<RouteInfo> routes) {
4155            for (RouteInfo route : routes) {
4156                try {
4157                    mNetd.setMarkedForwardingRoute(interfaze, route);
4158                } catch (RemoteException e) {
4159                }
4160            }
4161        }
4162
4163        public void setMarkedForwarding(String interfaze) {
4164            try {
4165                mNetd.setMarkedForwarding(interfaze);
4166            } catch (RemoteException e) {
4167            }
4168        }
4169
4170        public void clearMarkedForwarding(String interfaze) {
4171            try {
4172                mNetd.clearMarkedForwarding(interfaze);
4173            } catch (RemoteException e) {
4174            }
4175        }
4176
4177        public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
4178            int uidStart = uid * UserHandle.PER_USER_RANGE;
4179            int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
4180            addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
4181        }
4182
4183        public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
4184            int uidStart = uid * UserHandle.PER_USER_RANGE;
4185            int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
4186            clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
4187        }
4188
4189        public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
4190                boolean forwardDns) {
4191            // TODO: Re-enable this when the netId of the VPN is known.
4192            // try {
4193            //     mNetd.setUidRangeRoute(netId, uidStart, uidEnd, forwardDns);
4194            // } catch (RemoteException e) {
4195            // }
4196
4197        }
4198
4199        public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
4200                boolean forwardDns) {
4201            // TODO: Re-enable this when the netId of the VPN is known.
4202            // try {
4203            //     mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
4204            // } catch (RemoteException e) {
4205            // }
4206
4207        }
4208    }
4209
4210    @Override
4211    public boolean updateLockdownVpn() {
4212        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4213            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
4214            return false;
4215        }
4216
4217        // Tear down existing lockdown if profile was removed
4218        mLockdownEnabled = LockdownVpnTracker.isEnabled();
4219        if (mLockdownEnabled) {
4220            if (!mKeyStore.isUnlocked()) {
4221                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
4222                return false;
4223            }
4224
4225            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
4226            final VpnProfile profile = VpnProfile.decode(
4227                    profileName, mKeyStore.get(Credentials.VPN + profileName));
4228            int user = UserHandle.getUserId(Binder.getCallingUid());
4229            synchronized(mVpns) {
4230                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
4231                            profile));
4232            }
4233        } else {
4234            setLockdownTracker(null);
4235        }
4236
4237        return true;
4238    }
4239
4240    /**
4241     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
4242     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
4243     */
4244    private void setLockdownTracker(LockdownVpnTracker tracker) {
4245        // Shutdown any existing tracker
4246        final LockdownVpnTracker existing = mLockdownTracker;
4247        mLockdownTracker = null;
4248        if (existing != null) {
4249            existing.shutdown();
4250        }
4251
4252        try {
4253            if (tracker != null) {
4254                mNetd.setFirewallEnabled(true);
4255                mNetd.setFirewallInterfaceRule("lo", true);
4256                mLockdownTracker = tracker;
4257                mLockdownTracker.init();
4258            } else {
4259                mNetd.setFirewallEnabled(false);
4260            }
4261        } catch (RemoteException e) {
4262            // ignored; NMS lives inside system_server
4263        }
4264    }
4265
4266    private void throwIfLockdownEnabled() {
4267        if (mLockdownEnabled) {
4268            throw new IllegalStateException("Unavailable in lockdown mode");
4269        }
4270    }
4271
4272    public void supplyMessenger(int networkType, Messenger messenger) {
4273        enforceConnectivityInternalPermission();
4274
4275        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
4276            mNetTrackers[networkType].supplyMessenger(messenger);
4277        }
4278    }
4279
4280    public int findConnectionTypeForIface(String iface) {
4281        enforceConnectivityInternalPermission();
4282
4283        if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
4284        for (NetworkStateTracker tracker : mNetTrackers) {
4285            if (tracker != null) {
4286                LinkProperties lp = tracker.getLinkProperties();
4287                if (lp != null && iface.equals(lp.getInterfaceName())) {
4288                    return tracker.getNetworkInfo().getType();
4289                }
4290            }
4291        }
4292        return ConnectivityManager.TYPE_NONE;
4293    }
4294
4295    /**
4296     * Have mobile data fail fast if enabled.
4297     *
4298     * @param enabled DctConstants.ENABLED/DISABLED
4299     */
4300    private void setEnableFailFastMobileData(int enabled) {
4301        int tag;
4302
4303        if (enabled == DctConstants.ENABLED) {
4304            tag = mEnableFailFastMobileDataTag.incrementAndGet();
4305        } else {
4306            tag = mEnableFailFastMobileDataTag.get();
4307        }
4308        mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
4309                         enabled));
4310    }
4311
4312    private boolean isMobileDataStateTrackerReady() {
4313        MobileDataStateTracker mdst =
4314                (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4315        return (mdst != null) && (mdst.isReady());
4316    }
4317
4318    /**
4319     * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
4320     */
4321
4322    /**
4323     * No connection was possible to the network.
4324     * This is NOT a warm sim.
4325     */
4326    private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
4327
4328    /**
4329     * A connection was made to the internet, all is well.
4330     * This is NOT a warm sim.
4331     */
4332    private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
4333
4334    /**
4335     * A connection was made but no dns server was available to resolve a name to address.
4336     * This is NOT a warm sim since provisioning network is supported.
4337     */
4338    private static final int CMP_RESULT_CODE_NO_DNS = 2;
4339
4340    /**
4341     * A connection was made but could not open a TCP connection.
4342     * This is NOT a warm sim since provisioning network is supported.
4343     */
4344    private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
4345
4346    /**
4347     * A connection was made but there was a redirection, we appear to be in walled garden.
4348     * This is an indication of a warm sim on a mobile network such as T-Mobile.
4349     */
4350    private static final int CMP_RESULT_CODE_REDIRECTED = 4;
4351
4352    /**
4353     * The mobile network is a provisioning network.
4354     * This is an indication of a warm sim on a mobile network such as AT&T.
4355     */
4356    private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
4357
4358    /**
4359     * The mobile network is provisioning
4360     */
4361    private static final int CMP_RESULT_CODE_IS_PROVISIONING = 6;
4362
4363    private AtomicBoolean mIsProvisioningNetwork = new AtomicBoolean(false);
4364    private AtomicBoolean mIsStartingProvisioning = new AtomicBoolean(false);
4365
4366    private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
4367
4368    @Override
4369    public int checkMobileProvisioning(int suggestedTimeOutMs) {
4370        int timeOutMs = -1;
4371        if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
4372        enforceConnectivityInternalPermission();
4373
4374        final long token = Binder.clearCallingIdentity();
4375        try {
4376            timeOutMs = suggestedTimeOutMs;
4377            if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
4378                timeOutMs = CheckMp.MAX_TIMEOUT_MS;
4379            }
4380
4381            // Check that mobile networks are supported
4382            if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
4383                    || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
4384                if (DBG) log("checkMobileProvisioning: X no mobile network");
4385                return timeOutMs;
4386            }
4387
4388            // If we're already checking don't do it again
4389            // TODO: Add a queue of results...
4390            if (mIsCheckingMobileProvisioning.getAndSet(true)) {
4391                if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
4392                return timeOutMs;
4393            }
4394
4395            // Start off with mobile notification off
4396            setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
4397
4398            CheckMp checkMp = new CheckMp(mContext, this);
4399            CheckMp.CallBack cb = new CheckMp.CallBack() {
4400                @Override
4401                void onComplete(Integer result) {
4402                    if (DBG) log("CheckMp.onComplete: result=" + result);
4403                    NetworkInfo ni =
4404                            mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
4405                    switch(result) {
4406                        case CMP_RESULT_CODE_CONNECTABLE:
4407                        case CMP_RESULT_CODE_NO_CONNECTION:
4408                        case CMP_RESULT_CODE_NO_DNS:
4409                        case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
4410                            if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
4411                            break;
4412                        }
4413                        case CMP_RESULT_CODE_REDIRECTED: {
4414                            if (DBG) log("CheckMp.onComplete: warm sim");
4415                            String url = getMobileProvisioningUrl();
4416                            if (TextUtils.isEmpty(url)) {
4417                                url = getMobileRedirectedProvisioningUrl();
4418                            }
4419                            if (TextUtils.isEmpty(url) == false) {
4420                                if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
4421                                setProvNotificationVisible(true,
4422                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
4423                                        url);
4424                            } else {
4425                                if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
4426                            }
4427                            break;
4428                        }
4429                        case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
4430                            String url = getMobileProvisioningUrl();
4431                            if (TextUtils.isEmpty(url) == false) {
4432                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
4433                                setProvNotificationVisible(true,
4434                                        ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
4435                                        url);
4436                                // Mark that we've got a provisioning network and
4437                                // Disable Mobile Data until user actually starts provisioning.
4438                                mIsProvisioningNetwork.set(true);
4439                                MobileDataStateTracker mdst = (MobileDataStateTracker)
4440                                        mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4441                                mdst.setInternalDataEnable(false);
4442                            } else {
4443                                if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
4444                            }
4445                            break;
4446                        }
4447                        case CMP_RESULT_CODE_IS_PROVISIONING: {
4448                            // FIXME: Need to know when provisioning is done. Probably we can
4449                            // check the completion status if successful we're done if we
4450                            // "timedout" or still connected to provisioning APN turn off data?
4451                            if (DBG) log("CheckMp.onComplete: provisioning started");
4452                            mIsStartingProvisioning.set(false);
4453                            break;
4454                        }
4455                        default: {
4456                            loge("CheckMp.onComplete: ignore unexpected result=" + result);
4457                            break;
4458                        }
4459                    }
4460                    mIsCheckingMobileProvisioning.set(false);
4461                }
4462            };
4463            CheckMp.Params params =
4464                    new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
4465            if (DBG) log("checkMobileProvisioning: params=" + params);
4466            // TODO: Reenable when calls to the now defunct
4467            //       MobileDataStateTracker.isProvisioningNetwork() are removed.
4468            //       This code should be moved to the Telephony code.
4469            // checkMp.execute(params);
4470        } finally {
4471            Binder.restoreCallingIdentity(token);
4472            if (DBG) log("checkMobileProvisioning: X");
4473        }
4474        return timeOutMs;
4475    }
4476
4477    static class CheckMp extends
4478            AsyncTask<CheckMp.Params, Void, Integer> {
4479        private static final String CHECKMP_TAG = "CheckMp";
4480
4481        // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
4482        private static boolean mTestingFailures;
4483
4484        // Choosing 4 loops as half of them will use HTTPS and the other half HTTP
4485        private static final int MAX_LOOPS = 4;
4486
4487        // Number of milli-seconds to complete all of the retires
4488        public static final int MAX_TIMEOUT_MS =  60000;
4489
4490        // The socket should retry only 5 seconds, the default is longer
4491        private static final int SOCKET_TIMEOUT_MS = 5000;
4492
4493        // Sleep time for network errors
4494        private static final int NET_ERROR_SLEEP_SEC = 3;
4495
4496        // Sleep time for network route establishment
4497        private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
4498
4499        // Short sleep time for polling :(
4500        private static final int POLLING_SLEEP_SEC = 1;
4501
4502        private Context mContext;
4503        private ConnectivityService mCs;
4504        private TelephonyManager mTm;
4505        private Params mParams;
4506
4507        /**
4508         * Parameters for AsyncTask.execute
4509         */
4510        static class Params {
4511            private String mUrl;
4512            private long mTimeOutMs;
4513            private CallBack mCb;
4514
4515            Params(String url, long timeOutMs, CallBack cb) {
4516                mUrl = url;
4517                mTimeOutMs = timeOutMs;
4518                mCb = cb;
4519            }
4520
4521            @Override
4522            public String toString() {
4523                return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
4524            }
4525        }
4526
4527        // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
4528        // issued by name or ip address, for Google its by name so when we construct
4529        // this HostnameVerifier we'll pass the original Uri and use it to verify
4530        // the host. If the host name in the original uril fails we'll test the
4531        // hostname parameter just incase things change.
4532        static class CheckMpHostnameVerifier implements HostnameVerifier {
4533            Uri mOrgUri;
4534
4535            CheckMpHostnameVerifier(Uri orgUri) {
4536                mOrgUri = orgUri;
4537            }
4538
4539            @Override
4540            public boolean verify(String hostname, SSLSession session) {
4541                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
4542                String orgUriHost = mOrgUri.getHost();
4543                boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
4544                if (DBG) {
4545                    log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
4546                        + " orgUriHost=" + orgUriHost);
4547                }
4548                return retVal;
4549            }
4550        }
4551
4552        /**
4553         * The call back object passed in Params. onComplete will be called
4554         * on the main thread.
4555         */
4556        abstract static class CallBack {
4557            // Called on the main thread.
4558            abstract void onComplete(Integer result);
4559        }
4560
4561        public CheckMp(Context context, ConnectivityService cs) {
4562            if (Build.IS_DEBUGGABLE) {
4563                mTestingFailures =
4564                        SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
4565            } else {
4566                mTestingFailures = false;
4567            }
4568
4569            mContext = context;
4570            mCs = cs;
4571
4572            // Setup access to TelephonyService we'll be using.
4573            mTm = (TelephonyManager) mContext.getSystemService(
4574                    Context.TELEPHONY_SERVICE);
4575        }
4576
4577        /**
4578         * Get the default url to use for the test.
4579         */
4580        public String getDefaultUrl() {
4581            // See http://go/clientsdns for usage approval
4582            String server = Settings.Global.getString(mContext.getContentResolver(),
4583                    Settings.Global.CAPTIVE_PORTAL_SERVER);
4584            if (server == null) {
4585                server = "clients3.google.com";
4586            }
4587            return "http://" + server + "/generate_204";
4588        }
4589
4590        /**
4591         * Detect if its possible to connect to the http url. DNS based detection techniques
4592         * do not work at all hotspots. The best way to check is to perform a request to
4593         * a known address that fetches the data we expect.
4594         */
4595        private synchronized Integer isMobileOk(Params params) {
4596            Integer result = CMP_RESULT_CODE_NO_CONNECTION;
4597            Uri orgUri = Uri.parse(params.mUrl);
4598            Random rand = new Random();
4599            mParams = params;
4600
4601            if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
4602                result = CMP_RESULT_CODE_NO_CONNECTION;
4603                log("isMobileOk: X not mobile capable result=" + result);
4604                return result;
4605            }
4606
4607            if (mCs.mIsStartingProvisioning.get()) {
4608                result = CMP_RESULT_CODE_IS_PROVISIONING;
4609                log("isMobileOk: X is provisioning result=" + result);
4610                return result;
4611            }
4612
4613            // See if we've already determined we've got a provisioning connection,
4614            // if so we don't need to do anything active.
4615            MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
4616                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4617            boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
4618            log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
4619
4620            MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
4621                    mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4622            boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
4623            log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
4624
4625            if (isDefaultProvisioning || isHipriProvisioning) {
4626                result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4627                log("isMobileOk: X default || hipri is provisioning result=" + result);
4628                return result;
4629            }
4630
4631            try {
4632                // Continue trying to connect until time has run out
4633                long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
4634
4635                if (!mCs.isMobileDataStateTrackerReady()) {
4636                    // Wait for MobileDataStateTracker to be ready.
4637                    if (DBG) log("isMobileOk: mdst is not ready");
4638                    while(SystemClock.elapsedRealtime() < endTime) {
4639                        if (mCs.isMobileDataStateTrackerReady()) {
4640                            // Enable fail fast as we'll do retries here and use a
4641                            // hipri connection so the default connection stays active.
4642                            if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
4643                            mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
4644                            break;
4645                        }
4646                        sleep(POLLING_SLEEP_SEC);
4647                    }
4648                }
4649
4650                log("isMobileOk: start hipri url=" + params.mUrl);
4651
4652                // First wait until we can start using hipri
4653                Binder binder = new Binder();
4654                while(SystemClock.elapsedRealtime() < endTime) {
4655                    int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4656                            Phone.FEATURE_ENABLE_HIPRI, binder);
4657                    if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
4658                        || (ret == PhoneConstants.APN_REQUEST_STARTED)) {
4659                            log("isMobileOk: hipri started");
4660                            break;
4661                    }
4662                    if (VDBG) log("isMobileOk: hipri not started yet");
4663                    result = CMP_RESULT_CODE_NO_CONNECTION;
4664                    sleep(POLLING_SLEEP_SEC);
4665                }
4666
4667                // Continue trying to connect until time has run out
4668                while(SystemClock.elapsedRealtime() < endTime) {
4669                    try {
4670                        // Wait for hipri to connect.
4671                        // TODO: Don't poll and handle situation where hipri fails
4672                        // because default is retrying. See b/9569540
4673                        NetworkInfo.State state = mCs
4674                                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4675                        if (state != NetworkInfo.State.CONNECTED) {
4676                            if (true/*VDBG*/) {
4677                                log("isMobileOk: not connected ni=" +
4678                                    mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4679                            }
4680                            sleep(POLLING_SLEEP_SEC);
4681                            result = CMP_RESULT_CODE_NO_CONNECTION;
4682                            continue;
4683                        }
4684
4685                        // Hipri has started check if this is a provisioning url
4686                        MobileDataStateTracker mdst = (MobileDataStateTracker)
4687                                mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
4688                        if (mdst.isProvisioningNetwork()) {
4689                            result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
4690                            if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
4691                            return result;
4692                        } else {
4693                            if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
4694                        }
4695
4696                        // Get of the addresses associated with the url host. We need to use the
4697                        // address otherwise HttpURLConnection object will use the name to get
4698                        // the addresses and will try every address but that will bypass the
4699                        // route to host we setup and the connection could succeed as the default
4700                        // interface might be connected to the internet via wifi or other interface.
4701                        InetAddress[] addresses;
4702                        try {
4703                            addresses = InetAddress.getAllByName(orgUri.getHost());
4704                        } catch (UnknownHostException e) {
4705                            result = CMP_RESULT_CODE_NO_DNS;
4706                            log("isMobileOk: X UnknownHostException result=" + result);
4707                            return result;
4708                        }
4709                        log("isMobileOk: addresses=" + inetAddressesToString(addresses));
4710
4711                        // Get the type of addresses supported by this link
4712                        LinkProperties lp = mCs.getLinkPropertiesForTypeInternal(
4713                                ConnectivityManager.TYPE_MOBILE_HIPRI);
4714                        boolean linkHasIpv4 = lp.hasIPv4Address();
4715                        boolean linkHasIpv6 = lp.hasIPv6Address();
4716                        log("isMobileOk: linkHasIpv4=" + linkHasIpv4
4717                                + " linkHasIpv6=" + linkHasIpv6);
4718
4719                        final ArrayList<InetAddress> validAddresses =
4720                                new ArrayList<InetAddress>(addresses.length);
4721
4722                        for (InetAddress addr : addresses) {
4723                            if (((addr instanceof Inet4Address) && linkHasIpv4) ||
4724                                    ((addr instanceof Inet6Address) && linkHasIpv6)) {
4725                                validAddresses.add(addr);
4726                            }
4727                        }
4728
4729                        if (validAddresses.size() == 0) {
4730                            return CMP_RESULT_CODE_NO_CONNECTION;
4731                        }
4732
4733                        int addrTried = 0;
4734                        while (true) {
4735                            // Loop through at most MAX_LOOPS valid addresses or until
4736                            // we run out of time
4737                            if (addrTried++ >= MAX_LOOPS) {
4738                                log("isMobileOk: too many loops tried - giving up");
4739                                break;
4740                            }
4741                            if (SystemClock.elapsedRealtime() >= endTime) {
4742                                log("isMobileOk: spend too much time - giving up");
4743                                break;
4744                            }
4745
4746                            InetAddress hostAddr = validAddresses.get(rand.nextInt(
4747                                    validAddresses.size()));
4748
4749                            // Make a route to host so we check the specific interface.
4750                            if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
4751                                    hostAddr.getAddress(), null)) {
4752                                // Wait a short time to be sure the route is established ??
4753                                log("isMobileOk:"
4754                                        + " wait to establish route to hostAddr=" + hostAddr);
4755                                sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
4756                            } else {
4757                                log("isMobileOk:"
4758                                        + " could not establish route to hostAddr=" + hostAddr);
4759                                // Wait a short time before the next attempt
4760                                sleep(NET_ERROR_SLEEP_SEC);
4761                                continue;
4762                            }
4763
4764                            // Rewrite the url to have numeric address to use the specific route
4765                            // using http for half the attempts and https for the other half.
4766                            // Doing https first and http second as on a redirected walled garden
4767                            // such as t-mobile uses we get a SocketTimeoutException: "SSL
4768                            // handshake timed out" which we declare as
4769                            // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
4770                            // having http second we will be using logic used for some time.
4771                            URL newUrl;
4772                            String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
4773                            newUrl = new URL(scheme, hostAddr.getHostAddress(),
4774                                        orgUri.getPath());
4775                            log("isMobileOk: newUrl=" + newUrl);
4776
4777                            HttpURLConnection urlConn = null;
4778                            try {
4779                                // Open the connection set the request headers and get the response
4780                                urlConn = (HttpURLConnection)newUrl.openConnection(
4781                                        java.net.Proxy.NO_PROXY);
4782                                if (scheme.equals("https")) {
4783                                    ((HttpsURLConnection)urlConn).setHostnameVerifier(
4784                                            new CheckMpHostnameVerifier(orgUri));
4785                                }
4786                                urlConn.setInstanceFollowRedirects(false);
4787                                urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
4788                                urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
4789                                urlConn.setUseCaches(false);
4790                                urlConn.setAllowUserInteraction(false);
4791                                // Set the "Connection" to "Close" as by default "Keep-Alive"
4792                                // is used which is useless in this case.
4793                                urlConn.setRequestProperty("Connection", "close");
4794                                int responseCode = urlConn.getResponseCode();
4795
4796                                // For debug display the headers
4797                                Map<String, List<String>> headers = urlConn.getHeaderFields();
4798                                log("isMobileOk: headers=" + headers);
4799
4800                                // Close the connection
4801                                urlConn.disconnect();
4802                                urlConn = null;
4803
4804                                if (mTestingFailures) {
4805                                    // Pretend no connection, this tests using http and https
4806                                    result = CMP_RESULT_CODE_NO_CONNECTION;
4807                                    log("isMobileOk: TESTING_FAILURES, pretend no connction");
4808                                    continue;
4809                                }
4810
4811                                if (responseCode == 204) {
4812                                    // Return
4813                                    result = CMP_RESULT_CODE_CONNECTABLE;
4814                                    log("isMobileOk: X got expected responseCode=" + responseCode
4815                                            + " result=" + result);
4816                                    return result;
4817                                } else {
4818                                    // Retry to be sure this was redirected, we've gotten
4819                                    // occasions where a server returned 200 even though
4820                                    // the device didn't have a "warm" sim.
4821                                    log("isMobileOk: not expected responseCode=" + responseCode);
4822                                    // TODO - it would be nice in the single-address case to do
4823                                    // another DNS resolve here, but flushing the cache is a bit
4824                                    // heavy-handed.
4825                                    result = CMP_RESULT_CODE_REDIRECTED;
4826                                }
4827                            } catch (Exception e) {
4828                                log("isMobileOk: HttpURLConnection Exception" + e);
4829                                result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
4830                                if (urlConn != null) {
4831                                    urlConn.disconnect();
4832                                    urlConn = null;
4833                                }
4834                                sleep(NET_ERROR_SLEEP_SEC);
4835                                continue;
4836                            }
4837                        }
4838                        log("isMobileOk: X loops|timed out result=" + result);
4839                        return result;
4840                    } catch (Exception e) {
4841                        log("isMobileOk: Exception e=" + e);
4842                        continue;
4843                    }
4844                }
4845                log("isMobileOk: timed out");
4846            } finally {
4847                log("isMobileOk: F stop hipri");
4848                mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
4849                mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
4850                        Phone.FEATURE_ENABLE_HIPRI);
4851
4852                // Wait for hipri to disconnect.
4853                long endTime = SystemClock.elapsedRealtime() + 5000;
4854
4855                while(SystemClock.elapsedRealtime() < endTime) {
4856                    NetworkInfo.State state = mCs
4857                            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
4858                    if (state != NetworkInfo.State.DISCONNECTED) {
4859                        if (VDBG) {
4860                            log("isMobileOk: connected ni=" +
4861                                mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
4862                        }
4863                        sleep(POLLING_SLEEP_SEC);
4864                        continue;
4865                    }
4866                }
4867
4868                log("isMobileOk: X result=" + result);
4869            }
4870            return result;
4871        }
4872
4873        @Override
4874        protected Integer doInBackground(Params... params) {
4875            return isMobileOk(params[0]);
4876        }
4877
4878        @Override
4879        protected void onPostExecute(Integer result) {
4880            log("onPostExecute: result=" + result);
4881            if ((mParams != null) && (mParams.mCb != null)) {
4882                mParams.mCb.onComplete(result);
4883            }
4884        }
4885
4886        private String inetAddressesToString(InetAddress[] addresses) {
4887            StringBuffer sb = new StringBuffer();
4888            boolean firstTime = true;
4889            for(InetAddress addr : addresses) {
4890                if (firstTime) {
4891                    firstTime = false;
4892                } else {
4893                    sb.append(",");
4894                }
4895                sb.append(addr);
4896            }
4897            return sb.toString();
4898        }
4899
4900        private void printNetworkInfo() {
4901            boolean hasIccCard = mTm.hasIccCard();
4902            int simState = mTm.getSimState();
4903            log("hasIccCard=" + hasIccCard
4904                    + " simState=" + simState);
4905            NetworkInfo[] ni = mCs.getAllNetworkInfo();
4906            if (ni != null) {
4907                log("ni.length=" + ni.length);
4908                for (NetworkInfo netInfo: ni) {
4909                    log("netInfo=" + netInfo.toString());
4910                }
4911            } else {
4912                log("no network info ni=null");
4913            }
4914        }
4915
4916        /**
4917         * Sleep for a few seconds then return.
4918         * @param seconds
4919         */
4920        private static void sleep(int seconds) {
4921            long stopTime = System.nanoTime() + (seconds * 1000000000);
4922            long sleepTime;
4923            while ((sleepTime = stopTime - System.nanoTime()) > 0) {
4924                try {
4925                    Thread.sleep(sleepTime / 1000000);
4926                } catch (InterruptedException ignored) {
4927                }
4928            }
4929        }
4930
4931        private static void log(String s) {
4932            Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
4933        }
4934    }
4935
4936    // TODO: Move to ConnectivityManager and make public?
4937    private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
4938            "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
4939
4940    private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
4941        @Override
4942        public void onReceive(Context context, Intent intent) {
4943            if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
4944                handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
4945            }
4946        }
4947    };
4948
4949    private void handleMobileProvisioningAction(String url) {
4950        // Mark notification as not visible
4951        setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
4952
4953        // If provisioning network handle as a special case,
4954        // otherwise launch browser with the intent directly.
4955        if (mIsProvisioningNetwork.get()) {
4956            if (DBG) log("handleMobileProvisioningAction: on prov network enable then launch");
4957//            mIsStartingProvisioning.set(true);
4958//            MobileDataStateTracker mdst = (MobileDataStateTracker)
4959//                    mNetTrackers[ConnectivityManager.TYPE_MOBILE];
4960//            mdst.setEnableFailFastMobileData(DctConstants.ENABLED);
4961//            mdst.enableMobileProvisioning(url);
4962        } else {
4963            if (DBG) log("handleMobileProvisioningAction: not prov network");
4964            // Check for  apps that can handle provisioning first
4965            Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP);
4966            provisioningIntent.addCategory(TelephonyIntents.CATEGORY_MCCMNC_PREFIX
4967                    + mTelephonyManager.getSimOperator());
4968            if (mContext.getPackageManager().resolveActivity(provisioningIntent, 0 /* flags */)
4969                    != null) {
4970                provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4971                        Intent.FLAG_ACTIVITY_NEW_TASK);
4972                mContext.startActivity(provisioningIntent);
4973            } else {
4974                // If no apps exist, use standard URL ACTION_VIEW method
4975                Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
4976                        Intent.CATEGORY_APP_BROWSER);
4977                newIntent.setData(Uri.parse(url));
4978                newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
4979                        Intent.FLAG_ACTIVITY_NEW_TASK);
4980                try {
4981                    mContext.startActivity(newIntent);
4982                } catch (ActivityNotFoundException e) {
4983                    loge("handleMobileProvisioningAction: startActivity failed" + e);
4984                }
4985            }
4986        }
4987    }
4988
4989    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
4990    private volatile boolean mIsNotificationVisible = false;
4991
4992    private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
4993            String url) {
4994        if (DBG) {
4995            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
4996                + " extraInfo=" + extraInfo + " url=" + url);
4997        }
4998
4999        Resources r = Resources.getSystem();
5000        NotificationManager notificationManager = (NotificationManager) mContext
5001            .getSystemService(Context.NOTIFICATION_SERVICE);
5002
5003        if (visible) {
5004            CharSequence title;
5005            CharSequence details;
5006            int icon;
5007            Intent intent;
5008            Notification notification = new Notification();
5009            switch (networkType) {
5010                case ConnectivityManager.TYPE_WIFI:
5011                    title = r.getString(R.string.wifi_available_sign_in, 0);
5012                    details = r.getString(R.string.network_available_sign_in_detailed,
5013                            extraInfo);
5014                    icon = R.drawable.stat_notify_wifi_in_range;
5015                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
5016                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
5017                            Intent.FLAG_ACTIVITY_NEW_TASK);
5018                    notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
5019                    break;
5020                case ConnectivityManager.TYPE_MOBILE:
5021                case ConnectivityManager.TYPE_MOBILE_HIPRI:
5022                    title = r.getString(R.string.network_available_sign_in, 0);
5023                    // TODO: Change this to pull from NetworkInfo once a printable
5024                    // name has been added to it
5025                    details = mTelephonyManager.getNetworkOperatorName();
5026                    icon = R.drawable.stat_notify_rssi_in_range;
5027                    intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
5028                    intent.putExtra("EXTRA_URL", url);
5029                    intent.setFlags(0);
5030                    notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
5031                    break;
5032                default:
5033                    title = r.getString(R.string.network_available_sign_in, 0);
5034                    details = r.getString(R.string.network_available_sign_in_detailed,
5035                            extraInfo);
5036                    icon = R.drawable.stat_notify_rssi_in_range;
5037                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
5038                    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
5039                            Intent.FLAG_ACTIVITY_NEW_TASK);
5040                    notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
5041                    break;
5042            }
5043
5044            notification.when = 0;
5045            notification.icon = icon;
5046            notification.flags = Notification.FLAG_AUTO_CANCEL;
5047            notification.tickerText = title;
5048            notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
5049
5050            try {
5051                notificationManager.notify(NOTIFICATION_ID, networkType, notification);
5052            } catch (NullPointerException npe) {
5053                loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
5054                npe.printStackTrace();
5055            }
5056        } else {
5057            try {
5058                notificationManager.cancel(NOTIFICATION_ID, networkType);
5059            } catch (NullPointerException npe) {
5060                loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
5061                npe.printStackTrace();
5062            }
5063        }
5064        mIsNotificationVisible = visible;
5065    }
5066
5067    /** Location to an updatable file listing carrier provisioning urls.
5068     *  An example:
5069     *
5070     * <?xml version="1.0" encoding="utf-8"?>
5071     *  <provisioningUrls>
5072     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
5073     *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
5074     *  </provisioningUrls>
5075     */
5076    private static final String PROVISIONING_URL_PATH =
5077            "/data/misc/radio/provisioning_urls.xml";
5078    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
5079
5080    /** XML tag for root element. */
5081    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
5082    /** XML tag for individual url */
5083    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
5084    /** XML tag for redirected url */
5085    private static final String TAG_REDIRECTED_URL = "redirectedUrl";
5086    /** XML attribute for mcc */
5087    private static final String ATTR_MCC = "mcc";
5088    /** XML attribute for mnc */
5089    private static final String ATTR_MNC = "mnc";
5090
5091    private static final int REDIRECTED_PROVISIONING = 1;
5092    private static final int PROVISIONING = 2;
5093
5094    private String getProvisioningUrlBaseFromFile(int type) {
5095        FileReader fileReader = null;
5096        XmlPullParser parser = null;
5097        Configuration config = mContext.getResources().getConfiguration();
5098        String tagType;
5099
5100        switch (type) {
5101            case PROVISIONING:
5102                tagType = TAG_PROVISIONING_URL;
5103                break;
5104            case REDIRECTED_PROVISIONING:
5105                tagType = TAG_REDIRECTED_URL;
5106                break;
5107            default:
5108                throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
5109                        type);
5110        }
5111
5112        try {
5113            fileReader = new FileReader(mProvisioningUrlFile);
5114            parser = Xml.newPullParser();
5115            parser.setInput(fileReader);
5116            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
5117
5118            while (true) {
5119                XmlUtils.nextElement(parser);
5120
5121                String element = parser.getName();
5122                if (element == null) break;
5123
5124                if (element.equals(tagType)) {
5125                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
5126                    try {
5127                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
5128                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
5129                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
5130                                parser.next();
5131                                if (parser.getEventType() == XmlPullParser.TEXT) {
5132                                    return parser.getText();
5133                                }
5134                            }
5135                        }
5136                    } catch (NumberFormatException e) {
5137                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
5138                    }
5139                }
5140            }
5141            return null;
5142        } catch (FileNotFoundException e) {
5143            loge("Carrier Provisioning Urls file not found");
5144        } catch (XmlPullParserException e) {
5145            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
5146        } catch (IOException e) {
5147            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
5148        } finally {
5149            if (fileReader != null) {
5150                try {
5151                    fileReader.close();
5152                } catch (IOException e) {}
5153            }
5154        }
5155        return null;
5156    }
5157
5158    @Override
5159    public String getMobileRedirectedProvisioningUrl() {
5160        enforceConnectivityInternalPermission();
5161        String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
5162        if (TextUtils.isEmpty(url)) {
5163            url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
5164        }
5165        return url;
5166    }
5167
5168    @Override
5169    public String getMobileProvisioningUrl() {
5170        enforceConnectivityInternalPermission();
5171        String url = getProvisioningUrlBaseFromFile(PROVISIONING);
5172        if (TextUtils.isEmpty(url)) {
5173            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
5174            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
5175        } else {
5176            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
5177        }
5178        // populate the iccid, imei and phone number in the provisioning url.
5179        if (!TextUtils.isEmpty(url)) {
5180            String phoneNumber = mTelephonyManager.getLine1Number();
5181            if (TextUtils.isEmpty(phoneNumber)) {
5182                phoneNumber = "0000000000";
5183            }
5184            url = String.format(url,
5185                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
5186                    mTelephonyManager.getDeviceId() /* IMEI */,
5187                    phoneNumber /* Phone numer */);
5188        }
5189
5190        return url;
5191    }
5192
5193    @Override
5194    public void setProvisioningNotificationVisible(boolean visible, int networkType,
5195            String extraInfo, String url) {
5196        enforceConnectivityInternalPermission();
5197        setProvNotificationVisible(visible, networkType, extraInfo, url);
5198    }
5199
5200    @Override
5201    public void setAirplaneMode(boolean enable) {
5202        enforceConnectivityInternalPermission();
5203        final long ident = Binder.clearCallingIdentity();
5204        try {
5205            final ContentResolver cr = mContext.getContentResolver();
5206            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
5207            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5208            intent.putExtra("state", enable);
5209            mContext.sendBroadcast(intent);
5210        } finally {
5211            Binder.restoreCallingIdentity(ident);
5212        }
5213    }
5214
5215    private void onUserStart(int userId) {
5216        synchronized(mVpns) {
5217            Vpn userVpn = mVpns.get(userId);
5218            if (userVpn != null) {
5219                loge("Starting user already has a VPN");
5220                return;
5221            }
5222            userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
5223            mVpns.put(userId, userVpn);
5224            userVpn.startMonitoring(mContext, mTrackerHandler);
5225        }
5226    }
5227
5228    private void onUserStop(int userId) {
5229        synchronized(mVpns) {
5230            Vpn userVpn = mVpns.get(userId);
5231            if (userVpn == null) {
5232                loge("Stopping user has no VPN");
5233                return;
5234            }
5235            mVpns.delete(userId);
5236        }
5237    }
5238
5239    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
5240        @Override
5241        public void onReceive(Context context, Intent intent) {
5242            final String action = intent.getAction();
5243            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
5244            if (userId == UserHandle.USER_NULL) return;
5245
5246            if (Intent.ACTION_USER_STARTING.equals(action)) {
5247                onUserStart(userId);
5248            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
5249                onUserStop(userId);
5250            }
5251        }
5252    };
5253
5254    @Override
5255    public LinkQualityInfo getLinkQualityInfo(int networkType) {
5256        enforceAccessPermission();
5257        if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
5258            return mNetTrackers[networkType].getLinkQualityInfo();
5259        } else {
5260            return null;
5261        }
5262    }
5263
5264    @Override
5265    public LinkQualityInfo getActiveLinkQualityInfo() {
5266        enforceAccessPermission();
5267        if (isNetworkTypeValid(mActiveDefaultNetwork) &&
5268                mNetTrackers[mActiveDefaultNetwork] != null) {
5269            return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
5270        } else {
5271            return null;
5272        }
5273    }
5274
5275    @Override
5276    public LinkQualityInfo[] getAllLinkQualityInfo() {
5277        enforceAccessPermission();
5278        final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
5279        for (NetworkStateTracker tracker : mNetTrackers) {
5280            if (tracker != null) {
5281                LinkQualityInfo li = tracker.getLinkQualityInfo();
5282                if (li != null) {
5283                    result.add(li);
5284                }
5285            }
5286        }
5287
5288        return result.toArray(new LinkQualityInfo[result.size()]);
5289    }
5290
5291    /* Infrastructure for network sampling */
5292
5293    private void handleNetworkSamplingTimeout() {
5294
5295        log("Sampling interval elapsed, updating statistics ..");
5296
5297        // initialize list of interfaces ..
5298        Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
5299                new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
5300        for (NetworkStateTracker tracker : mNetTrackers) {
5301            if (tracker != null) {
5302                String ifaceName = tracker.getNetworkInterfaceName();
5303                if (ifaceName != null) {
5304                    mapIfaceToSample.put(ifaceName, null);
5305                }
5306            }
5307        }
5308
5309        // Read samples for all interfaces
5310        SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
5311
5312        // process samples for all networks
5313        for (NetworkStateTracker tracker : mNetTrackers) {
5314            if (tracker != null) {
5315                String ifaceName = tracker.getNetworkInterfaceName();
5316                SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
5317                if (ss != null) {
5318                    // end the previous sampling cycle
5319                    tracker.stopSampling(ss);
5320                    // start a new sampling cycle ..
5321                    tracker.startSampling(ss);
5322                }
5323            }
5324        }
5325
5326        log("Done.");
5327
5328        int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
5329                Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
5330                DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
5331
5332        if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
5333
5334        setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
5335    }
5336
5337    void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
5338        long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
5339        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
5340    }
5341
5342    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
5343            new HashMap<Messenger, NetworkFactoryInfo>();
5344    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
5345            new HashMap<NetworkRequest, NetworkRequestInfo>();
5346
5347    private static class NetworkFactoryInfo {
5348        public final String name;
5349        public final Messenger messenger;
5350        public final AsyncChannel asyncChannel;
5351
5352        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
5353            this.name = name;
5354            this.messenger = messenger;
5355            this.asyncChannel = asyncChannel;
5356        }
5357    }
5358
5359    private class NetworkRequestInfo implements IBinder.DeathRecipient {
5360        static final boolean REQUEST = true;
5361        static final boolean LISTEN = false;
5362
5363        final NetworkRequest request;
5364        IBinder mBinder;
5365        final int mPid;
5366        final int mUid;
5367        final Messenger messenger;
5368        final boolean isRequest;
5369
5370        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
5371            super();
5372            messenger = m;
5373            request = r;
5374            mBinder = binder;
5375            mPid = getCallingPid();
5376            mUid = getCallingUid();
5377            this.isRequest = isRequest;
5378
5379            try {
5380                mBinder.linkToDeath(this, 0);
5381            } catch (RemoteException e) {
5382                binderDied();
5383            }
5384        }
5385
5386        void unlinkDeathRecipient() {
5387            mBinder.unlinkToDeath(this, 0);
5388        }
5389
5390        public void binderDied() {
5391            log("ConnectivityService NetworkRequestInfo binderDied(" +
5392                    request + ", " + mBinder + ")");
5393            releaseNetworkRequest(request);
5394        }
5395
5396        public String toString() {
5397            return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
5398                    mPid + " for " + request;
5399        }
5400    }
5401
5402    @Override
5403    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
5404            Messenger messenger, int timeoutSec, IBinder binder, int legacyType) {
5405        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
5406                == false) {
5407            enforceConnectivityInternalPermission();
5408        } else {
5409            enforceChangePermission();
5410        }
5411
5412        if (timeoutSec < 0 || timeoutSec > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_SEC) {
5413            throw new IllegalArgumentException("Bad timeout specified");
5414        }
5415        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
5416                networkCapabilities), legacyType, nextNetworkRequestId());
5417        if (DBG) log("requestNetwork for " + networkRequest);
5418        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
5419                NetworkRequestInfo.REQUEST);
5420
5421        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
5422        if (timeoutSec > 0) {
5423            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
5424                    nri), timeoutSec * 1000);
5425        }
5426        return networkRequest;
5427    }
5428
5429    @Override
5430    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
5431            PendingIntent operation) {
5432        // TODO
5433        return null;
5434    }
5435
5436    @Override
5437    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
5438            Messenger messenger, IBinder binder) {
5439        enforceAccessPermission();
5440
5441        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
5442                networkCapabilities), TYPE_NONE, nextNetworkRequestId());
5443        if (DBG) log("listenForNetwork for " + networkRequest);
5444        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
5445                NetworkRequestInfo.LISTEN);
5446
5447        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
5448        return networkRequest;
5449    }
5450
5451    @Override
5452    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
5453            PendingIntent operation) {
5454    }
5455
5456    @Override
5457    public void releaseNetworkRequest(NetworkRequest networkRequest) {
5458        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST,
5459                networkRequest));
5460    }
5461
5462    @Override
5463    public void registerNetworkFactory(Messenger messenger, String name) {
5464        enforceConnectivityInternalPermission();
5465        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
5466        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
5467    }
5468
5469    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
5470        if (VDBG) log("Got NetworkFactory Messenger for " + nfi.name);
5471        mNetworkFactoryInfos.put(nfi.messenger, nfi);
5472        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
5473    }
5474
5475    @Override
5476    public void unregisterNetworkFactory(Messenger messenger) {
5477        enforceConnectivityInternalPermission();
5478        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
5479    }
5480
5481    private void handleUnregisterNetworkFactory(Messenger messenger) {
5482        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
5483        if (nfi == null) {
5484            if (VDBG) log("Failed to find Messenger in unregisterNetworkFactory");
5485            return;
5486        }
5487        if (VDBG) log("unregisterNetworkFactory for " + nfi.name);
5488    }
5489
5490    /**
5491     * NetworkAgentInfo supporting a request by requestId.
5492     * These have already been vetted (their Capabilities satisfy the request)
5493     * and the are the highest scored network available.
5494     * the are keyed off the Requests requestId.
5495     */
5496    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
5497            new SparseArray<NetworkAgentInfo>();
5498
5499    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
5500            new SparseArray<NetworkAgentInfo>();
5501
5502    // NetworkAgentInfo keyed off its connecting messenger
5503    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
5504    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
5505            new HashMap<Messenger, NetworkAgentInfo>();
5506
5507    private final NetworkRequest mDefaultRequest;
5508
5509    public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
5510            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
5511            int currentScore) {
5512        enforceConnectivityInternalPermission();
5513
5514        NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), nextNetId(),
5515            new NetworkInfo(networkInfo), new LinkProperties(linkProperties),
5516            new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler);
5517        if (VDBG) log("registerNetworkAgent " + nai);
5518        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
5519    }
5520
5521    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
5522        if (VDBG) log("Got NetworkAgent Messenger");
5523        mNetworkAgentInfos.put(na.messenger, na);
5524        mNetworkForNetId.put(na.network.netId, na);
5525        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
5526        NetworkInfo networkInfo = na.networkInfo;
5527        na.networkInfo = null;
5528        updateNetworkInfo(na, networkInfo);
5529    }
5530
5531    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
5532        LinkProperties newLp = networkAgent.linkProperties;
5533        int netId = networkAgent.network.netId;
5534
5535        updateInterfaces(newLp, oldLp, netId);
5536        updateMtu(newLp, oldLp);
5537        // TODO - figure out what to do for clat
5538//        for (LinkProperties lp : newLp.getStackedLinks()) {
5539//            updateMtu(lp, null);
5540//        }
5541        updateRoutes(newLp, oldLp, netId);
5542        updateDnses(newLp, oldLp, netId);
5543        updateClat(newLp, oldLp, networkAgent);
5544    }
5545
5546    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo na) {
5547        // Update 464xlat state.
5548        if (mClat.requiresClat(na)) {
5549
5550            // If the connection was previously using clat, but is not using it now, stop the clat
5551            // daemon. Normally, this happens automatically when the connection disconnects, but if
5552            // the disconnect is not reported, or if the connection's LinkProperties changed for
5553            // some other reason (e.g., handoff changes the IP addresses on the link), it would
5554            // still be running. If it's not running, then stopping it is a no-op.
5555            if (Nat464Xlat.isRunningClat(oldLp) && !Nat464Xlat.isRunningClat(newLp)) {
5556                mClat.stopClat();
5557            }
5558            // If the link requires clat to be running, then start the daemon now.
5559            if (na.networkInfo.isConnected()) {
5560                mClat.startClat(na);
5561            } else {
5562                mClat.stopClat();
5563            }
5564        }
5565    }
5566
5567    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
5568        CompareResult<String> interfaceDiff = new CompareResult<String>();
5569        if (oldLp != null) {
5570            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
5571        } else if (newLp != null) {
5572            interfaceDiff.added = newLp.getAllInterfaceNames();
5573        }
5574        for (String iface : interfaceDiff.added) {
5575            try {
5576                mNetd.addInterfaceToNetwork(iface, netId);
5577            } catch (Exception e) {
5578                loge("Exception adding interface: " + e);
5579            }
5580        }
5581        for (String iface : interfaceDiff.removed) {
5582            try {
5583                mNetd.removeInterfaceFromNetwork(iface, netId);
5584            } catch (Exception e) {
5585                loge("Exception removing interface: " + e);
5586            }
5587        }
5588    }
5589
5590    private void updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
5591        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
5592        if (oldLp != null) {
5593            routeDiff = oldLp.compareAllRoutes(newLp);
5594        } else if (newLp != null) {
5595            routeDiff.added = newLp.getAllRoutes();
5596        }
5597
5598        // add routes before removing old in case it helps with continuous connectivity
5599
5600        // do this twice, adding non-nexthop routes first, then routes they are dependent on
5601        for (RouteInfo route : routeDiff.added) {
5602            if (route.hasGateway()) continue;
5603            try {
5604                mNetd.addRoute(netId, route);
5605            } catch (Exception e) {
5606                loge("Exception in addRoute for non-gateway: " + e);
5607            }
5608        }
5609        for (RouteInfo route : routeDiff.added) {
5610            if (route.hasGateway() == false) continue;
5611            try {
5612                mNetd.addRoute(netId, route);
5613            } catch (Exception e) {
5614                loge("Exception in addRoute for gateway: " + e);
5615            }
5616        }
5617
5618        for (RouteInfo route : routeDiff.removed) {
5619            try {
5620                mNetd.removeRoute(netId, route);
5621            } catch (Exception e) {
5622                loge("Exception in removeRoute: " + e);
5623            }
5624        }
5625    }
5626    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
5627        if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
5628            Collection<InetAddress> dnses = newLp.getDnsServers();
5629            if (dnses.size() == 0 && mDefaultDns != null) {
5630                dnses = new ArrayList();
5631                dnses.add(mDefaultDns);
5632                if (DBG) {
5633                    loge("no dns provided for netId " + netId + ", so using defaults");
5634                }
5635            }
5636            try {
5637                mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
5638                    newLp.getDomains());
5639            } catch (Exception e) {
5640                loge("Exception in setDnsServersForNetwork: " + e);
5641            }
5642            NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
5643            if (defaultNai != null && defaultNai.network.netId == netId) {
5644                setDefaultDnsSystemProperties(dnses);
5645            }
5646        }
5647    }
5648
5649    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
5650        int last = 0;
5651        for (InetAddress dns : dnses) {
5652            ++last;
5653            String key = "net.dns" + last;
5654            String value = dns.getHostAddress();
5655            SystemProperties.set(key, value);
5656        }
5657        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
5658            String key = "net.dns" + i;
5659            SystemProperties.set(key, "");
5660        }
5661        mNumDnsEntries = last;
5662    }
5663
5664
5665    private void updateCapabilities(NetworkAgentInfo networkAgent,
5666            NetworkCapabilities networkCapabilities) {
5667        // TODO - what else here?  Verify still satisfies everybody?
5668        // Check if satisfies somebody new?  call callbacks?
5669        networkAgent.networkCapabilities = networkCapabilities;
5670    }
5671
5672    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
5673        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
5674        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
5675            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
5676                    networkRequest);
5677        }
5678    }
5679
5680    private void callCallbackForRequest(NetworkRequestInfo nri,
5681            NetworkAgentInfo networkAgent, int notificationType) {
5682        if (nri.messenger == null) return;  // Default request has no msgr
5683        Object o;
5684        int a1 = 0;
5685        int a2 = 0;
5686        switch (notificationType) {
5687            case ConnectivityManager.CALLBACK_LOSING:
5688                a1 = 30; // TODO - read this from NetworkMonitor
5689                // fall through
5690            case ConnectivityManager.CALLBACK_PRECHECK:
5691            case ConnectivityManager.CALLBACK_AVAILABLE:
5692            case ConnectivityManager.CALLBACK_LOST:
5693            case ConnectivityManager.CALLBACK_CAP_CHANGED:
5694            case ConnectivityManager.CALLBACK_IP_CHANGED: {
5695                o = new NetworkRequest(nri.request);
5696                a2 = networkAgent.network.netId;
5697                break;
5698            }
5699            case ConnectivityManager.CALLBACK_UNAVAIL:
5700            case ConnectivityManager.CALLBACK_RELEASED: {
5701                o = new NetworkRequest(nri.request);
5702                break;
5703            }
5704            default: {
5705                loge("Unknown notificationType " + notificationType);
5706                return;
5707            }
5708        }
5709        Message msg = Message.obtain();
5710        msg.arg1 = a1;
5711        msg.arg2 = a2;
5712        msg.obj = o;
5713        msg.what = notificationType;
5714        try {
5715            if (VDBG) log("sending notification " + notificationType + " for " + nri.request);
5716            nri.messenger.send(msg);
5717        } catch (RemoteException e) {
5718            // may occur naturally in the race of binder death.
5719            loge("RemoteException caught trying to send a callback msg for " + nri.request);
5720        }
5721    }
5722
5723    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5724        if (oldNetwork == null) {
5725            loge("Unknown NetworkAgentInfo in handleLingerComplete");
5726            return;
5727        }
5728        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
5729        if (DBG) {
5730            if (oldNetwork.networkRequests.size() != 0) {
5731                loge("Dead network still had " + oldNetwork.networkRequests.size() + " requests");
5732            }
5733        }
5734        oldNetwork.asyncChannel.disconnect();
5735    }
5736
5737    private void handleConnectionValidated(NetworkAgentInfo newNetwork) {
5738        if (newNetwork == null) {
5739            loge("Unknown NetworkAgentInfo in handleConnectionValidated");
5740            return;
5741        }
5742        boolean keep = false;
5743        boolean isNewDefault = false;
5744        if (DBG) log("handleConnectionValidated for "+newNetwork.name());
5745        // check if any NetworkRequest wants this NetworkAgent
5746        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
5747        if (VDBG) log(" new Network has: " + newNetwork.networkCapabilities);
5748        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5749            NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
5750            if (newNetwork == currentNetwork) {
5751                if (VDBG) log("Network " + newNetwork.name() + " was already satisfying" +
5752                              " request " + nri.request.requestId + ". No change.");
5753                keep = true;
5754                continue;
5755            }
5756
5757            // check if it satisfies the NetworkCapabilities
5758            if (VDBG) log("  checking if request is satisfied: " + nri.request);
5759            if (nri.request.networkCapabilities.satisfiedByNetworkCapabilities(
5760                    newNetwork.networkCapabilities)) {
5761                // next check if it's better than any current network we're using for
5762                // this request
5763                if (VDBG) {
5764                    log("currentScore = " +
5765                            (currentNetwork != null ? currentNetwork.currentScore : 0) +
5766                            ", newScore = " + newNetwork.currentScore);
5767                }
5768                if (currentNetwork == null ||
5769                        currentNetwork.currentScore < newNetwork.currentScore) {
5770                    if (currentNetwork != null) {
5771                        if (VDBG) log("   accepting network in place of " + currentNetwork.name());
5772                        currentNetwork.networkRequests.remove(nri.request.requestId);
5773                        currentNetwork.networkLingered.add(nri.request);
5774                        affectedNetworks.add(currentNetwork);
5775                    } else {
5776                        if (VDBG) log("   accepting network in place of null");
5777                    }
5778                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
5779                    newNetwork.addRequest(nri.request);
5780                    int legacyType = nri.request.legacyType;
5781                    if (legacyType != TYPE_NONE) {
5782                        mLegacyTypeTracker.add(legacyType, newNetwork);
5783                    }
5784                    keep = true;
5785                    // TODO - this could get expensive if we have alot of requests for this
5786                    // network.  Think about if there is a way to reduce this.  Push
5787                    // netid->request mapping to each factory?
5788                    sendUpdatedScoreToFactories(nri.request, newNetwork.currentScore);
5789                    if (mDefaultRequest.requestId == nri.request.requestId) {
5790                        isNewDefault = true;
5791                        updateActiveDefaultNetwork(newNetwork);
5792                        if (newNetwork.linkProperties != null) {
5793                            setDefaultDnsSystemProperties(
5794                                    newNetwork.linkProperties.getDnsServers());
5795                        } else {
5796                            setDefaultDnsSystemProperties(new ArrayList<InetAddress>());
5797                        }
5798                        mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5799                    }
5800                }
5801            }
5802        }
5803        for (NetworkAgentInfo nai : affectedNetworks) {
5804            boolean teardown = true;
5805            for (int i = 0; i < nai.networkRequests.size(); i++) {
5806                NetworkRequest nr = nai.networkRequests.valueAt(i);
5807                try {
5808                if (mNetworkRequests.get(nr).isRequest) {
5809                    teardown = false;
5810                }
5811                } catch (Exception e) {
5812                    loge("Request " + nr + " not found in mNetworkRequests.");
5813                    loge("  it came from request list  of " + nai.name());
5814                }
5815            }
5816            if (teardown) {
5817                nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
5818                notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
5819            } else {
5820                // not going to linger, so kill the list of linger networks..  only
5821                // notify them of linger if it happens as the result of gaining another,
5822                // but if they transition and old network stays up, don't tell them of linger
5823                // or very delayed loss
5824                nai.networkLingered.clear();
5825                if (VDBG) log("Lingered for " + nai.name() + " cleared");
5826            }
5827        }
5828        if (keep) {
5829            if (isNewDefault) {
5830                if (VDBG) log("Switching to new default network: " + newNetwork);
5831                setupDataActivityTracking(newNetwork);
5832                try {
5833                    mNetd.setDefaultNetId(newNetwork.network.netId);
5834                } catch (Exception e) {
5835                    loge("Exception setting default network :" + e);
5836                }
5837                if (newNetwork.equals(mNetworkForRequestId.get(mDefaultRequest.requestId))) {
5838                    handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
5839                }
5840                synchronized (ConnectivityService.this) {
5841                    // have a new default network, release the transition wakelock in
5842                    // a second if it's held.  The second pause is to allow apps
5843                    // to reconnect over the new network
5844                    if (mNetTransitionWakeLock.isHeld()) {
5845                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
5846                                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
5847                                mNetTransitionWakeLockSerialNumber, 0),
5848                                1000);
5849                    }
5850                }
5851
5852                // this will cause us to come up initially as unconnected and switching
5853                // to connected after our normal pause unless somebody reports us as
5854                // really disconnected
5855                mDefaultInetConditionPublished = 0;
5856                mDefaultConnectionSequence++;
5857                mInetConditionChangeInFlight = false;
5858                // TODO - read the tcp buffer size config string from somewhere
5859                // updateNetworkSettings();
5860            }
5861            // notify battery stats service about this network
5862            try {
5863                BatteryStatsService.getService().noteNetworkInterfaceType(
5864                        newNetwork.linkProperties.getInterfaceName(),
5865                        newNetwork.networkInfo.getType());
5866            } catch (RemoteException e) { }
5867            notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
5868        } else {
5869            if (DBG && newNetwork.networkRequests.size() != 0) {
5870                loge("tearing down network with live requests:");
5871                for (int i=0; i < newNetwork.networkRequests.size(); i++) {
5872                    loge("  " + newNetwork.networkRequests.valueAt(i));
5873                }
5874            }
5875            if (VDBG) log("Validated network turns out to be unwanted.  Tear it down.");
5876            newNetwork.asyncChannel.disconnect();
5877        }
5878    }
5879
5880
5881    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
5882        NetworkInfo.State state = newInfo.getState();
5883        NetworkInfo oldInfo = networkAgent.networkInfo;
5884        networkAgent.networkInfo = newInfo;
5885
5886        if (oldInfo != null && oldInfo.getState() == state) {
5887            if (VDBG) log("ignoring duplicate network state non-change");
5888            return;
5889        }
5890        if (DBG) {
5891            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5892                    (oldInfo == null ? "null" : oldInfo.getState()) +
5893                    " to " + state);
5894        }
5895
5896        if (state == NetworkInfo.State.CONNECTED) {
5897            try {
5898                // This is likely caused by the fact that this network already
5899                // exists. An example is when a network goes from CONNECTED to
5900                // CONNECTING and back (like wifi on DHCP renew).
5901                // TODO: keep track of which networks we've created, or ask netd
5902                // to tell us whether we've already created this network or not.
5903                mNetd.createNetwork(networkAgent.network.netId);
5904            } catch (Exception e) {
5905                loge("Error creating network " + networkAgent.network.netId + ": "
5906                        + e.getMessage());
5907                return;
5908            }
5909
5910            updateLinkProperties(networkAgent, null);
5911            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
5912            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
5913        } else if (state == NetworkInfo.State.DISCONNECTED ||
5914                state == NetworkInfo.State.SUSPENDED) {
5915            networkAgent.asyncChannel.disconnect();
5916        }
5917    }
5918
5919    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
5920        if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
5921
5922        nai.currentScore = score;
5923
5924        // TODO - This will not do the right thing if this network is lowering
5925        // its score and has requests that can be served by other
5926        // currently-active networks, or if the network is increasing its
5927        // score and other networks have requests that can be better served
5928        // by this network.
5929        //
5930        // Really we want to see if any of our requests migrate to other
5931        // active/lingered networks and if any other requests migrate to us (depending
5932        // on increasing/decreasing currentScore.  That's a bit of work and probably our
5933        // score checking/network allocation code needs to be modularized so we can understand
5934        // (see handleConnectionValided for an example).
5935        //
5936        // As a first order approx, lets just advertise the new score to factories.  If
5937        // somebody can beat it they will nominate a network and our normal net replacement
5938        // code will fire.
5939        for (int i = 0; i < nai.networkRequests.size(); i++) {
5940            NetworkRequest nr = nai.networkRequests.valueAt(i);
5941            sendUpdatedScoreToFactories(nr, score);
5942        }
5943    }
5944
5945    // notify only this one new request of the current state
5946    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5947        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
5948        // TODO - read state from monitor to decide what to send.
5949//        if (nai.networkMonitor.isLingering()) {
5950//            notifyType = NetworkCallbacks.LOSING;
5951//        } else if (nai.networkMonitor.isEvaluating()) {
5952//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
5953//        }
5954        callCallbackForRequest(nri, nai, notifyType);
5955    }
5956
5957    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
5958        if (connected) {
5959            NetworkInfo info = new NetworkInfo(nai.networkInfo);
5960            info.setType(type);
5961            sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
5962        } else {
5963            NetworkInfo info = new NetworkInfo(nai.networkInfo);
5964            info.setType(type);
5965            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5966            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5967            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5968            if (info.isFailover()) {
5969                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5970                nai.networkInfo.setFailover(false);
5971            }
5972            if (info.getReason() != null) {
5973                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5974            }
5975            if (info.getExtraInfo() != null) {
5976                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5977            }
5978            NetworkAgentInfo newDefaultAgent = null;
5979            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
5980                newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
5981                if (newDefaultAgent != null) {
5982                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5983                            newDefaultAgent.networkInfo);
5984                } else {
5985                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5986                }
5987            }
5988            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5989                    mDefaultInetConditionPublished);
5990            final Intent immediateIntent = new Intent(intent);
5991            immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
5992            sendStickyBroadcast(immediateIntent);
5993            sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
5994            if (newDefaultAgent != null) {
5995                sendConnectedBroadcastDelayed(newDefaultAgent.networkInfo,
5996                getConnectivityChangeDelay());
5997            }
5998        }
5999    }
6000
6001    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
6002        if (VDBG) log("notifyType " + notifyType + " for " + networkAgent.name());
6003        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
6004            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
6005            NetworkRequestInfo nri = mNetworkRequests.get(nr);
6006            if (VDBG) log(" sending notification for " + nr);
6007            callCallbackForRequest(nri, networkAgent, notifyType);
6008        }
6009    }
6010
6011    private LinkProperties getLinkPropertiesForTypeInternal(int networkType) {
6012        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
6013        return (nai != null) ?
6014                new LinkProperties(nai.linkProperties) :
6015                new LinkProperties();
6016    }
6017
6018    private NetworkInfo getNetworkInfoForType(int networkType) {
6019        if (!mLegacyTypeTracker.isTypeSupported(networkType))
6020            return null;
6021
6022        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
6023        if (nai != null) {
6024            NetworkInfo result = new NetworkInfo(nai.networkInfo);
6025            result.setType(networkType);
6026            return result;
6027        } else {
6028           return new NetworkInfo(networkType, 0, "Unknown", "");
6029        }
6030    }
6031
6032    private NetworkCapabilities getNetworkCapabilitiesForType(int networkType) {
6033        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
6034        return (nai != null) ?
6035                new NetworkCapabilities(nai.networkCapabilities) :
6036                new NetworkCapabilities();
6037    }
6038}
6039