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