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