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