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