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