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