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