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