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