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