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