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 android.app.Notification;
20import android.app.NotificationManager;
21import android.content.ContentResolver;
22import android.content.Context;
23import android.content.Intent;
24import android.content.pm.PackageManager;
25import android.net.ConnectivityManager;
26import android.net.IConnectivityManager;
27import android.net.MobileDataStateTracker;
28import android.net.NetworkInfo;
29import android.net.NetworkStateTracker;
30import android.net.wifi.WifiStateTracker;
31import android.os.Binder;
32import android.os.Handler;
33import android.os.IBinder;
34import android.os.Looper;
35import android.os.Message;
36import android.os.RemoteException;
37import android.os.ServiceManager;
38import android.os.SystemProperties;
39import android.provider.Settings;
40import android.text.TextUtils;
41import android.util.EventLog;
42import android.util.Log;
43
44import com.android.internal.telephony.Phone;
45
46import java.io.FileDescriptor;
47import java.io.PrintWriter;
48import java.util.ArrayList;
49import java.util.List;
50
51/**
52 * @hide
53 */
54public class ConnectivityService extends IConnectivityManager.Stub {
55
56    private static final boolean DBG = true;
57    private static final String TAG = "ConnectivityService";
58
59    // Event log tags (must be in sync with event-log-tags)
60    private static final int EVENTLOG_CONNECTIVITY_STATE_CHANGED = 50020;
61
62    // how long to wait before switching back to a radio's default network
63    private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
64    // system property that can override the above value
65    private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
66            "android.telephony.apn-restore";
67
68    /**
69     * Sometimes we want to refer to the individual network state
70     * trackers separately, and sometimes we just want to treat them
71     * abstractly.
72     */
73    private NetworkStateTracker mNetTrackers[];
74
75    /**
76     * A per Net list of the PID's that requested access to the net
77     * used both as a refcount and for per-PID DNS selection
78     */
79    private List mNetRequestersPids[];
80
81    private WifiWatchdogService mWifiWatchdogService;
82
83    // priority order of the nettrackers
84    // (excluding dynamically set mNetworkPreference)
85    // TODO - move mNetworkTypePreference into this
86    private int[] mPriorityList;
87
88    private Context mContext;
89    private int mNetworkPreference;
90    private int mActiveDefaultNetwork = -1;
91
92    private int mNumDnsEntries;
93
94    private boolean mTestMode;
95    private static ConnectivityService sServiceInstance;
96
97    private Handler mHandler;
98
99    // list of DeathRecipients used to make sure features are turned off when
100    // a process dies
101    private List mFeatureUsers;
102
103    private boolean mSystemReady;
104    private ArrayList<Intent> mDeferredBroadcasts;
105
106    private class NetworkAttributes {
107        /**
108         * Class for holding settings read from resources.
109         */
110        public String mName;
111        public int mType;
112        public int mRadio;
113        public int mPriority;
114        public NetworkInfo.State mLastState;
115        public NetworkAttributes(String init) {
116            String fragments[] = init.split(",");
117            mName = fragments[0].toLowerCase();
118            if (fragments[1].toLowerCase().equals("wifi")) {
119                mRadio = ConnectivityManager.TYPE_WIFI;
120            } else {
121                mRadio = ConnectivityManager.TYPE_MOBILE;
122            }
123            if (mName.equals("default")) {
124                mType = mRadio;
125            } else if (mName.equals("mms")) {
126                mType = ConnectivityManager.TYPE_MOBILE_MMS;
127            } else if (mName.equals("supl")) {
128                mType = ConnectivityManager.TYPE_MOBILE_SUPL;
129            } else if (mName.equals("dun")) {
130                mType = ConnectivityManager.TYPE_MOBILE_DUN;
131            } else if (mName.equals("hipri")) {
132                mType = ConnectivityManager.TYPE_MOBILE_HIPRI;
133            }
134            mPriority = Integer.parseInt(fragments[2]);
135            mLastState = NetworkInfo.State.UNKNOWN;
136        }
137        public boolean isDefault() {
138            return (mType == mRadio);
139        }
140    }
141    NetworkAttributes[] mNetAttributes;
142
143    private class RadioAttributes {
144        public String mName;
145        public int mPriority;
146        public int mSimultaneity;
147        public int mType;
148        public RadioAttributes(String init) {
149            String fragments[] = init.split(",");
150            mName = fragments[0].toLowerCase();
151            mPriority = Integer.parseInt(fragments[1]);
152            mSimultaneity = Integer.parseInt(fragments[2]);
153            if (mName.equals("wifi")) {
154                mType = ConnectivityManager.TYPE_WIFI;
155            } else {
156                mType = ConnectivityManager.TYPE_MOBILE;
157            }
158        }
159    }
160    RadioAttributes[] mRadioAttributes;
161
162    private static class ConnectivityThread extends Thread {
163        private Context mContext;
164
165        private ConnectivityThread(Context context) {
166            super("ConnectivityThread");
167            mContext = context;
168        }
169
170        @Override
171        public void run() {
172            Looper.prepare();
173            synchronized (this) {
174                sServiceInstance = new ConnectivityService(mContext);
175                notifyAll();
176            }
177            Looper.loop();
178        }
179
180        public static ConnectivityService getServiceInstance(Context context) {
181            ConnectivityThread thread = new ConnectivityThread(context);
182            thread.start();
183
184            synchronized (thread) {
185                while (sServiceInstance == null) {
186                    try {
187                        // Wait until sServiceInstance has been initialized.
188                        thread.wait();
189                    } catch (InterruptedException ignore) {
190                        Log.e(TAG,
191                            "Unexpected InterruptedException while waiting"+
192                            " for ConnectivityService thread");
193                    }
194                }
195            }
196
197            return sServiceInstance;
198        }
199    }
200
201    public static ConnectivityService getInstance(Context context) {
202        return ConnectivityThread.getServiceInstance(context);
203    }
204
205    private ConnectivityService(Context context) {
206        if (DBG) Log.v(TAG, "ConnectivityService starting up");
207        mContext = context;
208        mNetTrackers = new NetworkStateTracker[
209                ConnectivityManager.MAX_NETWORK_TYPE+1];
210        mHandler = new MyHandler();
211
212        mNetworkPreference = getPersistedNetworkPreference();
213
214        // Load device network attributes from resources
215        mNetAttributes = new NetworkAttributes[
216                ConnectivityManager.MAX_NETWORK_TYPE+1];
217        mRadioAttributes = new RadioAttributes[
218                ConnectivityManager.MAX_RADIO_TYPE+1];
219        String[] naStrings = context.getResources().getStringArray(
220                com.android.internal.R.array.networkAttributes);
221        // TODO - what if the setting has gaps/unknown types?
222        for (String a : naStrings) {
223            NetworkAttributes n = new NetworkAttributes(a);
224            mNetAttributes[n.mType] = n;
225        }
226        String[] raStrings = context.getResources().getStringArray(
227                com.android.internal.R.array.radioAttributes);
228        for (String a : raStrings) {
229            RadioAttributes r = new RadioAttributes(a);
230            mRadioAttributes[r.mType] = r;
231        }
232
233        // high priority first
234        mPriorityList = new int[naStrings.length];
235        {
236            int priority = 0; //lowest
237            int nextPos = naStrings.length-1;
238            while (nextPos>-1) {
239                for (int i = 0; i < mNetAttributes.length; i++) {
240                    if(mNetAttributes[i].mPriority == priority) {
241                        mPriorityList[nextPos--] = i;
242                    }
243                }
244                priority++;
245            }
246        }
247
248        mNetRequestersPids =
249                new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
250        for (int i=0; i<=ConnectivityManager.MAX_NETWORK_TYPE; i++) {
251            mNetRequestersPids[i] = new ArrayList();
252        }
253
254        mFeatureUsers = new ArrayList();
255
256        /*
257         * Create the network state trackers for Wi-Fi and mobile
258         * data. Maybe this could be done with a factory class,
259         * but it's not clear that it's worth it, given that
260         * the number of different network types is not going
261         * to change very often.
262         */
263        if (DBG) Log.v(TAG, "Starting Wifi Service.");
264        WifiStateTracker wst = new WifiStateTracker(context, mHandler);
265        WifiService wifiService = new WifiService(context, wst);
266        ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
267        mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
268
269        mNetTrackers[ConnectivityManager.TYPE_MOBILE] =
270                new MobileDataStateTracker(context, mHandler,
271                ConnectivityManager.TYPE_MOBILE, Phone.APN_TYPE_DEFAULT,
272                "MOBILE");
273
274        mNetTrackers[ConnectivityManager.TYPE_MOBILE_MMS] =
275                new MobileDataStateTracker(context, mHandler,
276                ConnectivityManager.TYPE_MOBILE_MMS, Phone.APN_TYPE_MMS,
277                "MOBILE_MMS");
278
279        mNetTrackers[ConnectivityManager.TYPE_MOBILE_SUPL] =
280                new MobileDataStateTracker(context, mHandler,
281                ConnectivityManager.TYPE_MOBILE_SUPL, Phone.APN_TYPE_SUPL,
282                "MOBILE_SUPL");
283
284        mNetTrackers[ConnectivityManager.TYPE_MOBILE_DUN] =
285                new MobileDataStateTracker(context, mHandler,
286                ConnectivityManager.TYPE_MOBILE_DUN, Phone.APN_TYPE_DUN,
287                "MOBILE_DUN");
288
289        mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI] =
290                new MobileDataStateTracker(context, mHandler,
291                ConnectivityManager.TYPE_MOBILE_HIPRI, Phone.APN_TYPE_HIPRI,
292                "MOBILE_HIPRI");
293
294        mNumDnsEntries = 0;
295
296        mTestMode = SystemProperties.get("cm.test.mode").equals("true")
297                && SystemProperties.get("ro.build.type").equals("eng");
298
299        for (NetworkStateTracker t : mNetTrackers)
300            t.startMonitoring();
301
302        // Constructing this starts it too
303        mWifiWatchdogService = new WifiWatchdogService(context, wst);
304    }
305
306    /**
307     * Sets the preferred network.
308     * @param preference the new preference
309     */
310    public synchronized void setNetworkPreference(int preference) {
311        enforceChangePermission();
312        if (ConnectivityManager.isNetworkTypeValid(preference) &&
313                mNetAttributes[preference].isDefault()) {
314            if (mNetworkPreference != preference) {
315                persistNetworkPreference(preference);
316                mNetworkPreference = preference;
317                enforcePreference();
318            }
319        }
320    }
321
322    public int getNetworkPreference() {
323        enforceAccessPermission();
324        return mNetworkPreference;
325    }
326
327    private void persistNetworkPreference(int networkPreference) {
328        final ContentResolver cr = mContext.getContentResolver();
329        Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE,
330                networkPreference);
331    }
332
333    private int getPersistedNetworkPreference() {
334        final ContentResolver cr = mContext.getContentResolver();
335
336        final int networkPrefSetting = Settings.Secure
337                .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
338        if (networkPrefSetting != -1) {
339            return networkPrefSetting;
340        }
341
342        return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
343    }
344
345    /**
346     * Make the state of network connectivity conform to the preference settings
347     * In this method, we only tear down a non-preferred network. Establishing
348     * a connection to the preferred network is taken care of when we handle
349     * the disconnect event from the non-preferred network
350     * (see {@link #handleDisconnect(NetworkInfo)}).
351     */
352    private void enforcePreference() {
353        if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
354            return;
355
356        if (!mNetTrackers[mNetworkPreference].isAvailable())
357            return;
358
359        for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
360            if (t != mNetworkPreference &&
361                    mNetTrackers[t].getNetworkInfo().isConnected()) {
362                if (DBG) {
363                    Log.d(TAG, "tearing down " +
364                            mNetTrackers[t].getNetworkInfo() +
365                            " in enforcePreference");
366                }
367                teardown(mNetTrackers[t]);
368            }
369        }
370    }
371
372    private boolean teardown(NetworkStateTracker netTracker) {
373        if (netTracker.teardown()) {
374            netTracker.setTeardownRequested(true);
375            return true;
376        } else {
377            return false;
378        }
379    }
380
381    /**
382     * Return NetworkInfo for the active (i.e., connected) network interface.
383     * It is assumed that at most one network is active at a time. If more
384     * than one is active, it is indeterminate which will be returned.
385     * @return the info for the active network, or {@code null} if none is
386     * active
387     */
388    public NetworkInfo getActiveNetworkInfo() {
389        enforceAccessPermission();
390        for (int type=0; type <= ConnectivityManager.MAX_NETWORK_TYPE; type++) {
391            if (!mNetAttributes[type].isDefault()) {
392                continue;
393            }
394            NetworkStateTracker t = mNetTrackers[type];
395            NetworkInfo info = t.getNetworkInfo();
396            if (info.isConnected()) {
397                if (DBG && type != mActiveDefaultNetwork) Log.e(TAG,
398                        "connected default network is not " +
399                        "mActiveDefaultNetwork!");
400                return info;
401            }
402        }
403        return null;
404    }
405
406    public NetworkInfo getNetworkInfo(int networkType) {
407        enforceAccessPermission();
408        if (ConnectivityManager.isNetworkTypeValid(networkType)) {
409            NetworkStateTracker t = mNetTrackers[networkType];
410            if (t != null)
411                return t.getNetworkInfo();
412        }
413        return null;
414    }
415
416    public NetworkInfo[] getAllNetworkInfo() {
417        enforceAccessPermission();
418        NetworkInfo[] result = new NetworkInfo[mNetTrackers.length];
419        int i = 0;
420        for (NetworkStateTracker t : mNetTrackers) {
421            result[i++] = t.getNetworkInfo();
422        }
423        return result;
424    }
425
426    public boolean setRadios(boolean turnOn) {
427        boolean result = true;
428        enforceChangePermission();
429        for (NetworkStateTracker t : mNetTrackers) {
430            result = t.setRadio(turnOn) && result;
431        }
432        return result;
433    }
434
435    public boolean setRadio(int netType, boolean turnOn) {
436        enforceChangePermission();
437        if (!ConnectivityManager.isNetworkTypeValid(netType)) {
438            return false;
439        }
440        NetworkStateTracker tracker = mNetTrackers[netType];
441        return tracker != null && tracker.setRadio(turnOn);
442    }
443
444    /**
445     * Used to notice when the calling process dies so we can self-expire
446     *
447     * Also used to know if the process has cleaned up after itself when
448     * our auto-expire timer goes off.  The timer has a link to an object.
449     *
450     */
451    private class FeatureUser implements IBinder.DeathRecipient {
452        int mNetworkType;
453        String mFeature;
454        IBinder mBinder;
455        int mPid;
456        int mUid;
457        long mCreateTime;
458
459        FeatureUser(int type, String feature, IBinder binder) {
460            super();
461            mNetworkType = type;
462            mFeature = feature;
463            mBinder = binder;
464            mPid = getCallingPid();
465            mUid = getCallingUid();
466            mCreateTime = System.currentTimeMillis();
467
468            try {
469                mBinder.linkToDeath(this, 0);
470            } catch (RemoteException e) {
471                binderDied();
472            }
473        }
474
475        void unlinkDeathRecipient() {
476            mBinder.unlinkToDeath(this, 0);
477        }
478
479        public void binderDied() {
480            Log.d(TAG, "ConnectivityService FeatureUser binderDied(" +
481                    mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
482                    (System.currentTimeMillis() - mCreateTime) + " mSec ago");
483            stopUsingNetworkFeature(this, false);
484        }
485
486        public void expire() {
487            Log.d(TAG, "ConnectivityService FeatureUser expire(" +
488                    mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
489                    (System.currentTimeMillis() - mCreateTime) + " mSec ago");
490            stopUsingNetworkFeature(this, false);
491        }
492
493        public String toString() {
494            return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
495                    (System.currentTimeMillis() - mCreateTime) + " mSec ago";
496        }
497    }
498
499    // javadoc from interface
500    public int startUsingNetworkFeature(int networkType, String feature,
501            IBinder binder) {
502        if (DBG) {
503            Log.d(TAG, "startUsingNetworkFeature for net " + networkType +
504                    ": " + feature);
505        }
506        enforceChangePermission();
507        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
508            return Phone.APN_REQUEST_FAILED;
509        }
510
511        FeatureUser f = new FeatureUser(networkType, feature, binder);
512
513        // TODO - move this into the MobileDataStateTracker
514        int usedNetworkType = networkType;
515        if(networkType == ConnectivityManager.TYPE_MOBILE) {
516            if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
517                usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
518            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
519                usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
520            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN)) {
521                usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
522            } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
523                usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
524            }
525        }
526        NetworkStateTracker network = mNetTrackers[usedNetworkType];
527        if (network != null) {
528            if (usedNetworkType != networkType) {
529                Integer currentPid = new Integer(getCallingPid());
530
531                NetworkStateTracker radio = mNetTrackers[networkType];
532                NetworkInfo ni = network.getNetworkInfo();
533
534                if (ni.isAvailable() == false) {
535                    if (DBG) Log.d(TAG, "special network not available");
536                    return Phone.APN_TYPE_NOT_AVAILABLE;
537                }
538
539                synchronized(this) {
540                    mFeatureUsers.add(f);
541                    if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
542                        // this gets used for per-pid dns when connected
543                        mNetRequestersPids[usedNetworkType].add(currentPid);
544                    }
545                }
546                mHandler.sendMessageDelayed(mHandler.obtainMessage(
547                        NetworkStateTracker.EVENT_RESTORE_DEFAULT_NETWORK,
548                        f), getRestoreDefaultNetworkDelay());
549
550
551                if ((ni.isConnectedOrConnecting() == true) &&
552                        !network.isTeardownRequested()) {
553                    if (ni.isConnected() == true) {
554                        // add the pid-specific dns
555                        handleDnsConfigurationChange();
556                        if (DBG) Log.d(TAG, "special network already active");
557                        return Phone.APN_ALREADY_ACTIVE;
558                    }
559                    if (DBG) Log.d(TAG, "special network already connecting");
560                    return Phone.APN_REQUEST_STARTED;
561                }
562
563                // check if the radio in play can make another contact
564                // assume if cannot for now
565
566                if (DBG) Log.d(TAG, "reconnecting to special network");
567                network.reconnect();
568                return Phone.APN_REQUEST_STARTED;
569            } else {
570                synchronized(this) {
571                    mFeatureUsers.add(f);
572                }
573                mHandler.sendMessageDelayed(mHandler.obtainMessage(
574                        NetworkStateTracker.EVENT_RESTORE_DEFAULT_NETWORK,
575                        f), getRestoreDefaultNetworkDelay());
576
577                return network.startUsingNetworkFeature(feature,
578                        getCallingPid(), getCallingUid());
579            }
580        }
581        return Phone.APN_TYPE_NOT_AVAILABLE;
582    }
583
584    // javadoc from interface
585    public int stopUsingNetworkFeature(int networkType, String feature) {
586        int pid = getCallingPid();
587        int uid = getCallingUid();
588
589        FeatureUser u = null;
590        boolean found = false;
591
592        synchronized(this) {
593            for (int i = 0; i < mFeatureUsers.size() ; i++) {
594                u = (FeatureUser)mFeatureUsers.get(i);
595                if (uid == u.mUid && pid == u.mPid &&
596                        networkType == u.mNetworkType &&
597                        TextUtils.equals(feature, u.mFeature)) {
598                    found = true;
599                    break;
600                }
601            }
602        }
603        if (found && u != null) {
604            // stop regardless of how many other time this proc had called start
605            return stopUsingNetworkFeature(u, true);
606        } else {
607            // none found!
608            if (DBG) Log.d(TAG, "ignoring stopUsingNetworkFeature - not a live request");
609            return 1;
610        }
611    }
612
613    private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
614        int networkType = u.mNetworkType;
615        String feature = u.mFeature;
616        int pid = u.mPid;
617        int uid = u.mUid;
618
619        NetworkStateTracker tracker = null;
620        boolean callTeardown = false;  // used to carry our decision outside of sync block
621
622        if (DBG) {
623            Log.d(TAG, "stopUsingNetworkFeature for net " + networkType +
624                    ": " + feature);
625        }
626        enforceChangePermission();
627        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
628            return -1;
629        }
630
631        // need to link the mFeatureUsers list with the mNetRequestersPids state in this
632        // sync block
633        synchronized(this) {
634            // check if this process still has an outstanding start request
635            if (!mFeatureUsers.contains(u)) {
636                return 1;
637            }
638            u.unlinkDeathRecipient();
639            mFeatureUsers.remove(mFeatureUsers.indexOf(u));
640            // If we care about duplicate requests, check for that here.
641            //
642            // This is done to support the extension of a request - the app
643            // can request we start the network feature again and renew the
644            // auto-shutoff delay.  Normal "stop" calls from the app though
645            // do not pay attention to duplicate requests - in effect the
646            // API does not refcount and a single stop will counter multiple starts.
647            if (ignoreDups == false) {
648                for (int i = 0; i < mFeatureUsers.size() ; i++) {
649                    FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
650                    if (x.mUid == u.mUid && x.mPid == u.mPid &&
651                            x.mNetworkType == u.mNetworkType &&
652                            TextUtils.equals(x.mFeature, u.mFeature)) {
653                        if (DBG) Log.d(TAG, "ignoring stopUsingNetworkFeature as dup is found");
654                        return 1;
655                    }
656                }
657            }
658
659            // TODO - move to MobileDataStateTracker
660            int usedNetworkType = networkType;
661            if (networkType == ConnectivityManager.TYPE_MOBILE) {
662                if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
663                    usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
664                } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
665                    usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
666                } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN)) {
667                    usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
668                } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
669                    usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
670                }
671            }
672            tracker =  mNetTrackers[usedNetworkType];
673            if(usedNetworkType != networkType) {
674                Integer currentPid = new Integer(pid);
675                mNetRequestersPids[usedNetworkType].remove(currentPid);
676                reassessPidDns(pid, true);
677                if (mNetRequestersPids[usedNetworkType].size() != 0) {
678                    if (DBG) Log.d(TAG, "not tearing down special network - " +
679                           "others still using it");
680                    return 1;
681                }
682                callTeardown = true;
683            }
684        }
685
686        if (callTeardown) {
687            tracker.teardown();
688            return 1;
689        } else {
690            // do it the old fashioned way
691            return tracker.stopUsingNetworkFeature(feature, pid, uid);
692        }
693    }
694
695    /**
696     * Ensure that a network route exists to deliver traffic to the specified
697     * host via the specified network interface.
698     * @param networkType the type of the network over which traffic to the
699     * specified host is to be routed
700     * @param hostAddress the IP address of the host to which the route is
701     * desired
702     * @return {@code true} on success, {@code false} on failure
703     */
704    public boolean requestRouteToHost(int networkType, int hostAddress) {
705        enforceChangePermission();
706        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
707            return false;
708        }
709        NetworkStateTracker tracker = mNetTrackers[networkType];
710
711        if (!tracker.getNetworkInfo().isConnected() || tracker.isTeardownRequested()) {
712            if (DBG) {
713                Log.d(TAG, "requestRouteToHost on down network (" + networkType + " - dropped");
714            }
715            return false;
716        }
717        return tracker.requestRouteToHost(hostAddress);
718    }
719
720    /**
721     * @see ConnectivityManager#getBackgroundDataSetting()
722     */
723    public boolean getBackgroundDataSetting() {
724        return Settings.Secure.getInt(mContext.getContentResolver(),
725                Settings.Secure.BACKGROUND_DATA, 1) == 1;
726    }
727
728    /**
729     * @see ConnectivityManager#setBackgroundDataSetting(boolean)
730     */
731    public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
732        mContext.enforceCallingOrSelfPermission(
733                android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
734                "ConnectivityService");
735
736        if (getBackgroundDataSetting() == allowBackgroundDataUsage) return;
737
738        Settings.Secure.putInt(mContext.getContentResolver(),
739                Settings.Secure.BACKGROUND_DATA,
740                allowBackgroundDataUsage ? 1 : 0);
741
742        Intent broadcast = new Intent(
743                ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
744        mContext.sendBroadcast(broadcast);
745    }
746
747    private int getNumConnectedNetworks() {
748        int numConnectedNets = 0;
749
750        for (NetworkStateTracker nt : mNetTrackers) {
751            if (nt.getNetworkInfo().isConnected() &&
752                    !nt.isTeardownRequested()) {
753                ++numConnectedNets;
754            }
755        }
756        return numConnectedNets;
757    }
758
759    private void enforceAccessPermission() {
760        mContext.enforceCallingOrSelfPermission(
761                android.Manifest.permission.ACCESS_NETWORK_STATE,
762                "ConnectivityService");
763    }
764
765    private void enforceChangePermission() {
766        mContext.enforceCallingOrSelfPermission(
767                android.Manifest.permission.CHANGE_NETWORK_STATE,
768                "ConnectivityService");
769    }
770
771    /**
772     * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
773     * network, we ignore it. If it is for the active network, we send out a
774     * broadcast. But first, we check whether it might be possible to connect
775     * to a different network.
776     * @param info the {@code NetworkInfo} for the network
777     */
778    private void handleDisconnect(NetworkInfo info) {
779
780        int prevNetType = info.getType();
781
782        mNetTrackers[prevNetType].setTeardownRequested(false);
783        /*
784         * If the disconnected network is not the active one, then don't report
785         * this as a loss of connectivity. What probably happened is that we're
786         * getting the disconnect for a network that we explicitly disabled
787         * in accordance with network preference policies.
788         */
789        if (!mNetAttributes[prevNetType].isDefault()) {
790            List pids = mNetRequestersPids[prevNetType];
791            for (int i = 0; i<pids.size(); i++) {
792                Integer pid = (Integer)pids.get(i);
793                // will remove them because the net's no longer connected
794                // need to do this now as only now do we know the pids and
795                // can properly null things that are no longer referenced.
796                reassessPidDns(pid.intValue(), false);
797            }
798        }
799
800        Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
801        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
802        if (info.isFailover()) {
803            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
804            info.setFailover(false);
805        }
806        if (info.getReason() != null) {
807            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
808        }
809        if (info.getExtraInfo() != null) {
810            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
811                    info.getExtraInfo());
812        }
813
814        NetworkStateTracker newNet = null;
815        if (mNetAttributes[prevNetType].isDefault()) {
816            newNet = tryFailover(prevNetType);
817            if (newNet != null) {
818                NetworkInfo switchTo = newNet.getNetworkInfo();
819                intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
820            } else {
821                intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
822            }
823        }
824        // do this before we broadcast the change
825        handleConnectivityChange();
826
827        sendStickyBroadcast(intent);
828        /*
829         * If the failover network is already connected, then immediately send
830         * out a followup broadcast indicating successful failover
831         */
832        if (newNet != null && newNet.getNetworkInfo().isConnected()) {
833            sendConnectedBroadcast(newNet.getNetworkInfo());
834        }
835    }
836
837    // returns null if no failover available
838    private NetworkStateTracker tryFailover(int prevNetType) {
839        /*
840         * If this is a default network, check if other defaults are available
841         * or active
842         */
843        NetworkStateTracker newNet = null;
844        if (mNetAttributes[prevNetType].isDefault()) {
845            if (mActiveDefaultNetwork == prevNetType) {
846                mActiveDefaultNetwork = -1;
847            }
848
849            int newType = -1;
850            int newPriority = -1;
851            for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
852                if (checkType == prevNetType) {
853                    continue;
854                }
855                if (mNetAttributes[checkType].isDefault()) {
856                    /* TODO - if we have multiple nets we could use
857                     * we may want to put more thought into which we choose
858                     */
859                    if (checkType == mNetworkPreference) {
860                        newType = checkType;
861                        break;
862                    }
863                    if (mRadioAttributes[mNetAttributes[checkType].mRadio].
864                            mPriority > newPriority) {
865                        newType = checkType;
866                        newPriority = mRadioAttributes[mNetAttributes[newType].mRadio].mPriority;
867                    }
868                }
869            }
870
871            if (newType != -1) {
872                newNet = mNetTrackers[newType];
873                /**
874                 * See if the other network is available to fail over to.
875                 * If is not available, we enable it anyway, so that it
876                 * will be able to connect when it does become available,
877                 * but we report a total loss of connectivity rather than
878                 * report that we are attempting to fail over.
879                 */
880                if (newNet.isAvailable()) {
881                    NetworkInfo switchTo = newNet.getNetworkInfo();
882                    switchTo.setFailover(true);
883                    if (!switchTo.isConnectedOrConnecting() ||
884                            newNet.isTeardownRequested()) {
885                        newNet.reconnect();
886                    }
887                    if (DBG) {
888                        if (switchTo.isConnected()) {
889                            Log.v(TAG, "Switching to already connected " +
890                                    switchTo.getTypeName());
891                        } else {
892                            Log.v(TAG, "Attempting to switch to " +
893                                    switchTo.getTypeName());
894                        }
895                    }
896                } else {
897                    newNet.reconnect();
898                }
899            }
900        }
901
902        return newNet;
903    }
904
905    private void sendConnectedBroadcast(NetworkInfo info) {
906        Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
907        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
908        if (info.isFailover()) {
909            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
910            info.setFailover(false);
911        }
912        if (info.getReason() != null) {
913            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
914        }
915        if (info.getExtraInfo() != null) {
916            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
917                    info.getExtraInfo());
918        }
919        sendStickyBroadcast(intent);
920    }
921
922    /**
923     * Called when an attempt to fail over to another network has failed.
924     * @param info the {@link NetworkInfo} for the failed network
925     */
926    private void handleConnectionFailure(NetworkInfo info) {
927        mNetTrackers[info.getType()].setTeardownRequested(false);
928
929        String reason = info.getReason();
930        String extraInfo = info.getExtraInfo();
931
932        if (DBG) {
933            String reasonText;
934            if (reason == null) {
935                reasonText = ".";
936            } else {
937                reasonText = " (" + reason + ").";
938            }
939            Log.v(TAG, "Attempt to connect to " + info.getTypeName() +
940                    " failed" + reasonText);
941        }
942
943        Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
944        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
945        if (getActiveNetworkInfo() == null) {
946            intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
947        }
948        if (reason != null) {
949            intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
950        }
951        if (extraInfo != null) {
952            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
953        }
954        if (info.isFailover()) {
955            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
956            info.setFailover(false);
957        }
958
959        NetworkStateTracker newNet = null;
960        if (mNetAttributes[info.getType()].isDefault()) {
961            newNet = tryFailover(info.getType());
962            if (newNet != null) {
963                NetworkInfo switchTo = newNet.getNetworkInfo();
964                intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
965            } else {
966                intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
967            }
968        }
969
970        // do this before we broadcast the change
971        handleConnectivityChange();
972
973        sendStickyBroadcast(intent);
974        /*
975         * If the failover network is already connected, then immediately send
976         * out a followup broadcast indicating successful failover
977         */
978        if (newNet != null && newNet.getNetworkInfo().isConnected()) {
979            sendConnectedBroadcast(newNet.getNetworkInfo());
980        }
981    }
982
983    private void sendStickyBroadcast(Intent intent) {
984        synchronized(this) {
985            if (mSystemReady) {
986                mContext.sendStickyBroadcast(intent);
987            } else {
988                if (mDeferredBroadcasts == null) {
989                    mDeferredBroadcasts = new ArrayList<Intent>();
990                }
991                mDeferredBroadcasts.add(intent);
992            }
993        }
994    }
995
996    void systemReady() {
997        synchronized(this) {
998            mSystemReady = true;
999            if (mDeferredBroadcasts != null) {
1000                int count = mDeferredBroadcasts.size();
1001                for (int i = 0; i < count; i++) {
1002                    mContext.sendStickyBroadcast(mDeferredBroadcasts.get(i));
1003                }
1004                mDeferredBroadcasts = null;
1005            }
1006        }
1007    }
1008
1009    private void handleConnect(NetworkInfo info) {
1010        int type = info.getType();
1011
1012        // snapshot isFailover, because sendConnectedBroadcast() resets it
1013        boolean isFailover = info.isFailover();
1014        NetworkStateTracker thisNet = mNetTrackers[type];
1015
1016        // if this is a default net and other default is running
1017        // kill the one not preferred
1018        if (mNetAttributes[type].isDefault()) {
1019            if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1020                if ((type != mNetworkPreference &&
1021                        mNetAttributes[mActiveDefaultNetwork].mPriority >
1022                        mNetAttributes[type].mPriority) ||
1023                        mNetworkPreference == mActiveDefaultNetwork) {
1024                        // don't accept this one
1025                        if (DBG) Log.v(TAG, "Not broadcasting CONNECT_ACTION " +
1026                                "to torn down network " + info.getTypeName());
1027                        teardown(thisNet);
1028                        return;
1029                } else {
1030                    // tear down the other
1031                    NetworkStateTracker otherNet =
1032                            mNetTrackers[mActiveDefaultNetwork];
1033                    if (DBG) Log.v(TAG, "Policy requires " +
1034                            otherNet.getNetworkInfo().getTypeName() +
1035                            " teardown");
1036                    if (!teardown(otherNet)) {
1037                        Log.e(TAG, "Network declined teardown request");
1038                        return;
1039                    }
1040                    if (isFailover) {
1041                        otherNet.releaseWakeLock();
1042                    }
1043                }
1044            }
1045            mActiveDefaultNetwork = type;
1046        }
1047        thisNet.setTeardownRequested(false);
1048        thisNet.updateNetworkSettings();
1049        handleConnectivityChange();
1050        sendConnectedBroadcast(info);
1051    }
1052
1053    private void handleScanResultsAvailable(NetworkInfo info) {
1054        int networkType = info.getType();
1055        if (networkType != ConnectivityManager.TYPE_WIFI) {
1056            if (DBG) Log.v(TAG, "Got ScanResultsAvailable for " +
1057                    info.getTypeName() + " network. Don't know how to handle.");
1058        }
1059
1060        mNetTrackers[networkType].interpretScanResultsAvailable();
1061    }
1062
1063    private void handleNotificationChange(boolean visible, int id,
1064            Notification notification) {
1065        NotificationManager notificationManager = (NotificationManager) mContext
1066                .getSystemService(Context.NOTIFICATION_SERVICE);
1067
1068        if (visible) {
1069            notificationManager.notify(id, notification);
1070        } else {
1071            notificationManager.cancel(id);
1072        }
1073    }
1074
1075    /**
1076     * After any kind of change in the connectivity state of any network,
1077     * make sure that anything that depends on the connectivity state of
1078     * more than one network is set up correctly. We're mainly concerned
1079     * with making sure that the list of DNS servers is set up  according
1080     * to which networks are connected, and ensuring that the right routing
1081     * table entries exist.
1082     */
1083    private void handleConnectivityChange() {
1084        /*
1085         * If a non-default network is enabled, add the host routes that
1086         * will allow it's DNS servers to be accessed.  Only
1087         * If both mobile and wifi are enabled, add the host routes that
1088         * will allow MMS traffic to pass on the mobile network. But
1089         * remove the default route for the mobile network, so that there
1090         * will be only one default route, to ensure that all traffic
1091         * except MMS will travel via Wi-Fi.
1092         */
1093        handleDnsConfigurationChange();
1094
1095        for (int netType : mPriorityList) {
1096            if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
1097                if (mNetAttributes[netType].isDefault()) {
1098                    mNetTrackers[netType].addDefaultRoute();
1099                } else {
1100                    mNetTrackers[netType].addPrivateDnsRoutes();
1101                }
1102            } else {
1103                if (mNetAttributes[netType].isDefault()) {
1104                    mNetTrackers[netType].removeDefaultRoute();
1105                } else {
1106                    mNetTrackers[netType].removePrivateDnsRoutes();
1107                }
1108            }
1109        }
1110    }
1111
1112    /**
1113     * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1114     * on the highest priority active net which this process requested.
1115     * If there aren't any, clear it out
1116     */
1117    private void reassessPidDns(int myPid, boolean doBump)
1118    {
1119        if (DBG) Log.d(TAG, "reassessPidDns for pid " + myPid);
1120        for(int i : mPriorityList) {
1121            if (mNetAttributes[i].isDefault()) {
1122                continue;
1123            }
1124            NetworkStateTracker nt = mNetTrackers[i];
1125            if (nt.getNetworkInfo().isConnected() &&
1126                    !nt.isTeardownRequested()) {
1127                List pids = mNetRequestersPids[i];
1128                for (int j=0; j<pids.size(); j++) {
1129                    Integer pid = (Integer)pids.get(j);
1130                    if (pid.intValue() == myPid) {
1131                        String[] dnsList = nt.getNameServers();
1132                        writePidDns(dnsList, myPid);
1133                        if (doBump) {
1134                            bumpDns();
1135                        }
1136                        return;
1137                    }
1138                }
1139           }
1140        }
1141        // nothing found - delete
1142        for (int i = 1; ; i++) {
1143            String prop = "net.dns" + i + "." + myPid;
1144            if (SystemProperties.get(prop).length() == 0) {
1145                if (doBump) {
1146                    bumpDns();
1147                }
1148                return;
1149            }
1150            SystemProperties.set(prop, "");
1151        }
1152    }
1153
1154    private void writePidDns(String[] dnsList, int pid) {
1155        int j = 1;
1156        for (String dns : dnsList) {
1157            if (dns != null && !TextUtils.equals(dns, "0.0.0.0")) {
1158                SystemProperties.set("net.dns" + j++ + "." + pid, dns);
1159            }
1160        }
1161    }
1162
1163    private void bumpDns() {
1164        /*
1165         * Bump the property that tells the name resolver library to reread
1166         * the DNS server list from the properties.
1167         */
1168        String propVal = SystemProperties.get("net.dnschange");
1169        int n = 0;
1170        if (propVal.length() != 0) {
1171            try {
1172                n = Integer.parseInt(propVal);
1173            } catch (NumberFormatException e) {}
1174        }
1175        SystemProperties.set("net.dnschange", "" + (n+1));
1176    }
1177
1178    private void handleDnsConfigurationChange() {
1179        // add default net's dns entries
1180        for (int x = mPriorityList.length-1; x>= 0; x--) {
1181            int netType = mPriorityList[x];
1182            NetworkStateTracker nt = mNetTrackers[netType];
1183            if (nt != null && nt.getNetworkInfo().isConnected() &&
1184                    !nt.isTeardownRequested()) {
1185                String[] dnsList = nt.getNameServers();
1186                if (mNetAttributes[netType].isDefault()) {
1187                    int j = 1;
1188                    for (String dns : dnsList) {
1189                        if (dns != null && !TextUtils.equals(dns, "0.0.0.0")) {
1190                            if (DBG) {
1191                                Log.d(TAG, "adding dns " + dns + " for " +
1192                                        nt.getNetworkInfo().getTypeName());
1193                            }
1194                            SystemProperties.set("net.dns" + j++, dns);
1195                        }
1196                    }
1197                    for (int k=j ; k<mNumDnsEntries; k++) {
1198                        if (DBG) Log.d(TAG, "erasing net.dns" + k);
1199                        SystemProperties.set("net.dns" + k, "");
1200                    }
1201                    mNumDnsEntries = j;
1202                } else {
1203                    // set per-pid dns for attached secondary nets
1204                    List pids = mNetRequestersPids[netType];
1205                    for (int y=0; y< pids.size(); y++) {
1206                        Integer pid = (Integer)pids.get(y);
1207                        writePidDns(dnsList, pid.intValue());
1208                    }
1209                }
1210            }
1211        }
1212
1213        bumpDns();
1214    }
1215
1216    private int getRestoreDefaultNetworkDelay() {
1217        String restoreDefaultNetworkDelayStr = SystemProperties.get(
1218                NETWORK_RESTORE_DELAY_PROP_NAME);
1219        if(restoreDefaultNetworkDelayStr != null &&
1220                restoreDefaultNetworkDelayStr.length() != 0) {
1221            try {
1222                return Integer.valueOf(restoreDefaultNetworkDelayStr);
1223            } catch (NumberFormatException e) {
1224            }
1225        }
1226        return RESTORE_DEFAULT_NETWORK_DELAY;
1227    }
1228
1229    @Override
1230    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1231        if (mContext.checkCallingOrSelfPermission(
1232                android.Manifest.permission.DUMP)
1233                != PackageManager.PERMISSION_GRANTED) {
1234            pw.println("Permission Denial: can't dump ConnectivityService " +
1235                    "from from pid=" + Binder.getCallingPid() + ", uid=" +
1236                    Binder.getCallingUid());
1237            return;
1238        }
1239        pw.println();
1240        for (NetworkStateTracker nst : mNetTrackers) {
1241            if (nst != null) {
1242                if (nst.getNetworkInfo().isConnected()) {
1243                    pw.println("Active network: " + nst.getNetworkInfo().
1244                            getTypeName());
1245                }
1246                pw.println(nst.getNetworkInfo());
1247                pw.println(nst);
1248                pw.println();
1249            }
1250        }
1251
1252        pw.println("Network Requester Pids:");
1253        for (int net : mPriorityList) {
1254            String pidString = net + ": ";
1255            for (Object pid : mNetRequestersPids[net]) {
1256                pidString = pidString + pid.toString() + ", ";
1257            }
1258            pw.println(pidString);
1259        }
1260        pw.println();
1261
1262        pw.println("FeatureUsers:");
1263        for (Object requester : mFeatureUsers) {
1264            pw.println(requester.toString());
1265        }
1266        pw.println();
1267    }
1268
1269    // must be stateless - things change under us.
1270    private class MyHandler extends Handler {
1271        @Override
1272        public void handleMessage(Message msg) {
1273            NetworkInfo info;
1274            switch (msg.what) {
1275                case NetworkStateTracker.EVENT_STATE_CHANGED:
1276                    info = (NetworkInfo) msg.obj;
1277                    int type = info.getType();
1278                    NetworkInfo.State state = info.getState();
1279                    // only do this optimization for wifi.  It going into scan mode for location
1280                    // services generates alot of noise.  Meanwhile the mms apn won't send out
1281                    // subsequent notifications when on default cellular because it never
1282                    // disconnects..  so only do this to wifi notifications.  Fixed better when the
1283                    // APN notifications are standardized.
1284                    if (mNetAttributes[type].mLastState == state &&
1285                            mNetAttributes[type].mRadio == ConnectivityManager.TYPE_WIFI) {
1286                        if (DBG) {
1287                            // TODO - remove this after we validate the dropping doesn't break
1288                            // anything
1289                            Log.d(TAG, "Dropping ConnectivityChange for " +
1290                                    info.getTypeName() + ": " +
1291                                    state + "/" + info.getDetailedState());
1292                        }
1293                        return;
1294                    }
1295                    mNetAttributes[type].mLastState = state;
1296
1297                    if (DBG) Log.d(TAG, "ConnectivityChange for " +
1298                            info.getTypeName() + ": " +
1299                            state + "/" + info.getDetailedState());
1300
1301                    // Connectivity state changed:
1302                    // [31-13] Reserved for future use
1303                    // [12-9] Network subtype (for mobile network, as defined
1304                    //         by TelephonyManager)
1305                    // [8-3] Detailed state ordinal (as defined by
1306                    //         NetworkInfo.DetailedState)
1307                    // [2-0] Network type (as defined by ConnectivityManager)
1308                    int eventLogParam = (info.getType() & 0x7) |
1309                            ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1310                            (info.getSubtype() << 9);
1311                    EventLog.writeEvent(EVENTLOG_CONNECTIVITY_STATE_CHANGED,
1312                            eventLogParam);
1313
1314                    if (info.getDetailedState() ==
1315                            NetworkInfo.DetailedState.FAILED) {
1316                        handleConnectionFailure(info);
1317                    } else if (state == NetworkInfo.State.DISCONNECTED) {
1318                        handleDisconnect(info);
1319                    } else if (state == NetworkInfo.State.SUSPENDED) {
1320                        // TODO: need to think this over.
1321                        // the logic here is, handle SUSPENDED the same as
1322                        // DISCONNECTED. The only difference being we are
1323                        // broadcasting an intent with NetworkInfo that's
1324                        // suspended. This allows the applications an
1325                        // opportunity to handle DISCONNECTED and SUSPENDED
1326                        // differently, or not.
1327                        handleDisconnect(info);
1328                    } else if (state == NetworkInfo.State.CONNECTED) {
1329                        handleConnect(info);
1330                    }
1331                    break;
1332
1333                case NetworkStateTracker.EVENT_SCAN_RESULTS_AVAILABLE:
1334                    info = (NetworkInfo) msg.obj;
1335                    handleScanResultsAvailable(info);
1336                    break;
1337
1338                case NetworkStateTracker.EVENT_NOTIFICATION_CHANGED:
1339                    handleNotificationChange(msg.arg1 == 1, msg.arg2,
1340                            (Notification) msg.obj);
1341
1342                case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
1343                    handleDnsConfigurationChange();
1344                    break;
1345
1346                case NetworkStateTracker.EVENT_ROAMING_CHANGED:
1347                    // fill me in
1348                    break;
1349
1350                case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
1351                    // fill me in
1352                    break;
1353                case NetworkStateTracker.EVENT_RESTORE_DEFAULT_NETWORK:
1354                    FeatureUser u = (FeatureUser)msg.obj;
1355                    u.expire();
1356                    break;
1357            }
1358        }
1359    }
1360}
1361