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