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