ConnectivityService.java revision 5c3816f2ff3d40136da1e40eec792d8faf0e75dd
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.bluetooth.BluetoothTetheringDataTracker;
20import android.content.ContentResolver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.pm.PackageManager;
24import android.database.ContentObserver;
25import android.net.ConnectivityManager;
26import android.net.DummyDataStateTracker;
27import android.net.EthernetDataTracker;
28import android.net.IConnectivityManager;
29import android.net.LinkAddress;
30import android.net.LinkProperties;
31import android.net.MobileDataStateTracker;
32import android.net.NetworkConfig;
33import android.net.NetworkInfo;
34import android.net.NetworkStateTracker;
35import android.net.NetworkUtils;
36import android.net.Proxy;
37import android.net.ProxyProperties;
38import android.net.RouteInfo;
39import android.net.vpn.VpnManager;
40import android.net.wifi.WifiStateTracker;
41import android.os.Binder;
42import android.os.Handler;
43import android.os.HandlerThread;
44import android.os.IBinder;
45import android.os.INetworkManagementService;
46import android.os.Looper;
47import android.os.Message;
48import android.os.PowerManager;
49import android.os.RemoteException;
50import android.os.ServiceManager;
51import android.os.SystemProperties;
52import android.provider.Settings;
53import android.text.TextUtils;
54import android.util.EventLog;
55import android.util.Slog;
56
57import com.android.internal.telephony.Phone;
58import com.android.server.connectivity.Tethering;
59
60import java.io.FileDescriptor;
61import java.io.FileWriter;
62import java.io.IOException;
63import java.io.PrintWriter;
64import java.net.InetAddress;
65import java.net.Inet4Address;
66import java.net.UnknownHostException;
67import java.util.ArrayList;
68import java.util.Collection;
69import java.util.concurrent.atomic.AtomicBoolean;
70import java.util.GregorianCalendar;
71import java.util.List;
72
73/**
74 * @hide
75 */
76public class ConnectivityService extends IConnectivityManager.Stub {
77
78    private static final boolean DBG = true;
79    private static final String TAG = "ConnectivityService";
80
81    // how long to wait before switching back to a radio's default network
82    private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
83    // system property that can override the above value
84    private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
85            "android.telephony.apn-restore";
86
87    // used in recursive route setting to add gateways for the host for which
88    // a host route was requested.
89    private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
90
91    private Tethering mTethering;
92    private boolean mTetheringConfigValid = false;
93
94    /**
95     * Sometimes we want to refer to the individual network state
96     * trackers separately, and sometimes we just want to treat them
97     * abstractly.
98     */
99    private NetworkStateTracker mNetTrackers[];
100
101    /**
102     * A per Net list of the PID's that requested access to the net
103     * used both as a refcount and for per-PID DNS selection
104     */
105    private List mNetRequestersPids[];
106
107    private WifiWatchdogService mWifiWatchdogService;
108
109    // priority order of the nettrackers
110    // (excluding dynamically set mNetworkPreference)
111    // TODO - move mNetworkTypePreference into this
112    private int[] mPriorityList;
113
114    private Context mContext;
115    private int mNetworkPreference;
116    private int mActiveDefaultNetwork = -1;
117    // 0 is full bad, 100 is full good
118    private int mDefaultInetCondition = 0;
119    private int mDefaultInetConditionPublished = 0;
120    private boolean mInetConditionChangeInFlight = false;
121    private int mDefaultConnectionSequence = 0;
122
123    private int mNumDnsEntries;
124
125    private boolean mTestMode;
126    private static ConnectivityService sServiceInstance;
127
128    private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true);
129
130    private INetworkManagementService mNetd;
131
132    private static final int ENABLED  = 1;
133    private static final int DISABLED = 0;
134
135    // Share the event space with NetworkStateTracker (which can't see this
136    // internal class but sends us events).  If you change these, change
137    // NetworkStateTracker.java too.
138    private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1;
139    private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100;
140
141    /**
142     * used internally as a delayed event to make us switch back to the
143     * default network
144     */
145    private static final int EVENT_RESTORE_DEFAULT_NETWORK =
146            MAX_NETWORK_STATE_TRACKER_EVENT + 1;
147
148    /**
149     * used internally to change our mobile data enabled flag
150     */
151    private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED =
152            MAX_NETWORK_STATE_TRACKER_EVENT + 2;
153
154    /**
155     * used internally to change our network preference setting
156     * arg1 = networkType to prefer
157     */
158    private static final int EVENT_SET_NETWORK_PREFERENCE =
159            MAX_NETWORK_STATE_TRACKER_EVENT + 3;
160
161    /**
162     * used internally to synchronize inet condition reports
163     * arg1 = networkType
164     * arg2 = condition (0 bad, 100 good)
165     */
166    private static final int EVENT_INET_CONDITION_CHANGE =
167            MAX_NETWORK_STATE_TRACKER_EVENT + 4;
168
169    /**
170     * used internally to mark the end of inet condition hold periods
171     * arg1 = networkType
172     */
173    private static final int EVENT_INET_CONDITION_HOLD_END =
174            MAX_NETWORK_STATE_TRACKER_EVENT + 5;
175
176    /**
177     * used internally to set the background data preference
178     * arg1 = TRUE for enabled, FALSE for disabled
179     */
180    private static final int EVENT_SET_BACKGROUND_DATA =
181            MAX_NETWORK_STATE_TRACKER_EVENT + 6;
182
183    /**
184     * used internally to set enable/disable cellular data
185     * arg1 = ENBALED or DISABLED
186     */
187    private static final int EVENT_SET_MOBILE_DATA =
188            MAX_NETWORK_STATE_TRACKER_EVENT + 7;
189
190    /**
191     * used internally to clear a wakelock when transitioning
192     * from one net to another
193     */
194    private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK =
195            MAX_NETWORK_STATE_TRACKER_EVENT + 8;
196
197    /**
198     * used internally to reload global proxy settings
199     */
200    private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY =
201            MAX_NETWORK_STATE_TRACKER_EVENT + 9;
202
203    /**
204     * used internally to set external dependency met/unmet
205     * arg1 = ENABLED (met) or DISABLED (unmet)
206     * arg2 = NetworkType
207     */
208    private static final int EVENT_SET_DEPENDENCY_MET =
209            MAX_NETWORK_STATE_TRACKER_EVENT + 10;
210
211    private Handler mHandler;
212
213    // list of DeathRecipients used to make sure features are turned off when
214    // a process dies
215    private List mFeatureUsers;
216
217    private boolean mSystemReady;
218    private Intent mInitialBroadcast;
219
220    private PowerManager.WakeLock mNetTransitionWakeLock;
221    private String mNetTransitionWakeLockCausedBy = "";
222    private int mNetTransitionWakeLockSerialNumber;
223    private int mNetTransitionWakeLockTimeout;
224
225    private InetAddress mDefaultDns;
226
227    // used in DBG mode to track inet condition reports
228    private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
229    private ArrayList mInetLog;
230
231    // track the current default http proxy - tell the world if we get a new one (real change)
232    private ProxyProperties mDefaultProxy = null;
233    // track the global proxy.
234    private ProxyProperties mGlobalProxy = null;
235    private final Object mGlobalProxyLock = new Object();
236
237    private SettingsObserver mSettingsObserver;
238
239    NetworkConfig[] mNetConfigs;
240    int mNetworksDefined;
241
242    private static class RadioAttributes {
243        public int mSimultaneity;
244        public int mType;
245        public RadioAttributes(String init) {
246            String fragments[] = init.split(",");
247            mType = Integer.parseInt(fragments[0]);
248            mSimultaneity = Integer.parseInt(fragments[1]);
249        }
250    }
251    RadioAttributes[] mRadioAttributes;
252
253    public static synchronized ConnectivityService getInstance(Context context) {
254        if (sServiceInstance == null) {
255            sServiceInstance = new ConnectivityService(context);
256        }
257        return sServiceInstance;
258    }
259
260    private ConnectivityService(Context context) {
261        if (DBG) log("ConnectivityService starting up");
262
263        HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
264        handlerThread.start();
265        mHandler = new MyHandler(handlerThread.getLooper());
266
267        mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(),
268                Settings.Secure.BACKGROUND_DATA, 1) == 1);
269
270        // setup our unique device name
271        if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
272            String id = Settings.Secure.getString(context.getContentResolver(),
273                    Settings.Secure.ANDROID_ID);
274            if (id != null && id.length() > 0) {
275                String name = new String("android_").concat(id);
276                SystemProperties.set("net.hostname", name);
277            }
278        }
279
280        // read our default dns server ip
281        String dns = Settings.Secure.getString(context.getContentResolver(),
282                Settings.Secure.DEFAULT_DNS_SERVER);
283        if (dns == null || dns.length() == 0) {
284            dns = context.getResources().getString(
285                    com.android.internal.R.string.config_default_dns_server);
286        }
287        try {
288            mDefaultDns = NetworkUtils.numericToInetAddress(dns);
289        } catch (IllegalArgumentException e) {
290            loge("Error setting defaultDns using " + dns);
291        }
292
293        mContext = context;
294
295        PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
296        mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
297        mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
298                com.android.internal.R.integer.config_networkTransitionTimeout);
299
300        mNetTrackers = new NetworkStateTracker[
301                ConnectivityManager.MAX_NETWORK_TYPE+1];
302
303        mNetworkPreference = getPersistedNetworkPreference();
304
305        mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
306        mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
307
308        // Load device network attributes from resources
309        String[] raStrings = context.getResources().getStringArray(
310                com.android.internal.R.array.radioAttributes);
311        for (String raString : raStrings) {
312            RadioAttributes r = new RadioAttributes(raString);
313            if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
314                loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
315                continue;
316            }
317            if (mRadioAttributes[r.mType] != null) {
318                loge("Error in radioAttributes - ignoring attempt to redefine type " +
319                        r.mType);
320                continue;
321            }
322            mRadioAttributes[r.mType] = r;
323        }
324
325        String[] naStrings = context.getResources().getStringArray(
326                com.android.internal.R.array.networkAttributes);
327        for (String naString : naStrings) {
328            try {
329                NetworkConfig n = new NetworkConfig(naString);
330                if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
331                    loge("Error in networkAttributes - ignoring attempt to define type " +
332                            n.type);
333                    continue;
334                }
335                if (mNetConfigs[n.type] != null) {
336                    loge("Error in networkAttributes - ignoring attempt to redefine type " +
337                            n.type);
338                    continue;
339                }
340                if (mRadioAttributes[n.radio] == null) {
341                    loge("Error in networkAttributes - ignoring attempt to use undefined " +
342                            "radio " + n.radio + " in network type " + n.type);
343                    continue;
344                }
345                mNetConfigs[n.type] = n;
346                mNetworksDefined++;
347            } catch(Exception e) {
348                // ignore it - leave the entry null
349            }
350        }
351
352        // high priority first
353        mPriorityList = new int[mNetworksDefined];
354        {
355            int insertionPoint = mNetworksDefined-1;
356            int currentLowest = 0;
357            int nextLowest = 0;
358            while (insertionPoint > -1) {
359                for (NetworkConfig na : mNetConfigs) {
360                    if (na == null) continue;
361                    if (na.priority < currentLowest) continue;
362                    if (na.priority > currentLowest) {
363                        if (na.priority < nextLowest || nextLowest == 0) {
364                            nextLowest = na.priority;
365                        }
366                        continue;
367                    }
368                    mPriorityList[insertionPoint--] = na.type;
369                }
370                currentLowest = nextLowest;
371                nextLowest = 0;
372            }
373        }
374
375        mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
376        for (int i : mPriorityList) {
377            mNetRequestersPids[i] = new ArrayList();
378        }
379
380        mFeatureUsers = new ArrayList();
381
382        mNumDnsEntries = 0;
383
384        mTestMode = SystemProperties.get("cm.test.mode").equals("true")
385                && SystemProperties.get("ro.build.type").equals("eng");
386        /*
387         * Create the network state trackers for Wi-Fi and mobile
388         * data. Maybe this could be done with a factory class,
389         * but it's not clear that it's worth it, given that
390         * the number of different network types is not going
391         * to change very often.
392         */
393        for (int netType : mPriorityList) {
394            switch (mNetConfigs[netType].radio) {
395            case ConnectivityManager.TYPE_WIFI:
396                if (DBG) log("Starting Wifi Service.");
397                WifiStateTracker wst = new WifiStateTracker();
398                WifiService wifiService = new WifiService(context);
399                ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
400                wifiService.checkAndStartWifi();
401                mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
402                wst.startMonitoring(context, mHandler);
403
404                //TODO: as part of WWS refactor, create only when needed
405                mWifiWatchdogService = new WifiWatchdogService(context);
406
407                break;
408            case ConnectivityManager.TYPE_MOBILE:
409                mNetTrackers[netType] = new MobileDataStateTracker(netType,
410                        mNetConfigs[netType].name);
411                mNetTrackers[netType].startMonitoring(context, mHandler);
412                break;
413            case ConnectivityManager.TYPE_DUMMY:
414                mNetTrackers[netType] = new DummyDataStateTracker(netType,
415                        mNetConfigs[netType].name);
416                mNetTrackers[netType].startMonitoring(context, mHandler);
417                break;
418            case ConnectivityManager.TYPE_BLUETOOTH:
419                mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance();
420                mNetTrackers[netType].startMonitoring(context, mHandler);
421                break;
422            case ConnectivityManager.TYPE_ETHERNET:
423                mNetTrackers[netType] = EthernetDataTracker.getInstance();
424                mNetTrackers[netType].startMonitoring(context, mHandler);
425                break;
426            default:
427                loge("Trying to create a DataStateTracker for an unknown radio type " +
428                        mNetConfigs[netType].radio);
429                continue;
430            }
431        }
432
433        IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
434        INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b);
435
436        mTethering = new Tethering(mContext, nmService, mHandler.getLooper());
437        mTetheringConfigValid = (((mNetTrackers[ConnectivityManager.TYPE_MOBILE_DUN] != null) ||
438                                  !mTethering.isDunRequired()) &&
439                                 (mTethering.getTetherableUsbRegexs().length != 0 ||
440                                  mTethering.getTetherableWifiRegexs().length != 0 ||
441                                  mTethering.getTetherableBluetoothRegexs().length != 0) &&
442                                 mTethering.getUpstreamIfaceRegexs().length != 0);
443
444        if (DBG) {
445            mInetLog = new ArrayList();
446        }
447
448        mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
449        mSettingsObserver.observe(mContext);
450
451        loadGlobalProxy();
452
453        VpnManager.startVpnService(context);
454    }
455
456
457    /**
458     * Sets the preferred network.
459     * @param preference the new preference
460     */
461    public void setNetworkPreference(int preference) {
462        enforceChangePermission();
463
464        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
465    }
466
467    public int getNetworkPreference() {
468        enforceAccessPermission();
469        int preference;
470        synchronized(this) {
471            preference = mNetworkPreference;
472        }
473        return preference;
474    }
475
476    private void handleSetNetworkPreference(int preference) {
477        if (ConnectivityManager.isNetworkTypeValid(preference) &&
478                mNetConfigs[preference] != null &&
479                mNetConfigs[preference].isDefault()) {
480            if (mNetworkPreference != preference) {
481                final ContentResolver cr = mContext.getContentResolver();
482                Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference);
483                synchronized(this) {
484                    mNetworkPreference = preference;
485                }
486                enforcePreference();
487            }
488        }
489    }
490
491    private int getPersistedNetworkPreference() {
492        final ContentResolver cr = mContext.getContentResolver();
493
494        final int networkPrefSetting = Settings.Secure
495                .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1);
496        if (networkPrefSetting != -1) {
497            return networkPrefSetting;
498        }
499
500        return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE;
501    }
502
503    /**
504     * Make the state of network connectivity conform to the preference settings
505     * In this method, we only tear down a non-preferred network. Establishing
506     * a connection to the preferred network is taken care of when we handle
507     * the disconnect event from the non-preferred network
508     * (see {@link #handleDisconnect(NetworkInfo)}).
509     */
510    private void enforcePreference() {
511        if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
512            return;
513
514        if (!mNetTrackers[mNetworkPreference].isAvailable())
515            return;
516
517        for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
518            if (t != mNetworkPreference && mNetTrackers[t] != null &&
519                    mNetTrackers[t].getNetworkInfo().isConnected()) {
520                if (DBG) {
521                    log("tearing down " + mNetTrackers[t].getNetworkInfo() +
522                            " in enforcePreference");
523                }
524                teardown(mNetTrackers[t]);
525            }
526        }
527    }
528
529    private boolean teardown(NetworkStateTracker netTracker) {
530        if (netTracker.teardown()) {
531            netTracker.setTeardownRequested(true);
532            return true;
533        } else {
534            return false;
535        }
536    }
537
538    /**
539     * Return NetworkInfo for the active (i.e., connected) network interface.
540     * It is assumed that at most one network is active at a time. If more
541     * than one is active, it is indeterminate which will be returned.
542     * @return the info for the active network, or {@code null} if none is
543     * active
544     */
545    public NetworkInfo getActiveNetworkInfo() {
546        enforceAccessPermission();
547        if (mActiveDefaultNetwork != -1) {
548            return mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
549        }
550        return null;
551    }
552
553    public NetworkInfo getNetworkInfo(int networkType) {
554        enforceAccessPermission();
555        if (ConnectivityManager.isNetworkTypeValid(networkType)) {
556            NetworkStateTracker t = mNetTrackers[networkType];
557            if (t != null)
558                return t.getNetworkInfo();
559        }
560        return null;
561    }
562
563    public NetworkInfo[] getAllNetworkInfo() {
564        enforceAccessPermission();
565        NetworkInfo[] result = new NetworkInfo[mNetworksDefined];
566        int i = 0;
567        for (NetworkStateTracker t : mNetTrackers) {
568            if(t != null) result[i++] = t.getNetworkInfo();
569        }
570        return result;
571    }
572
573    /**
574     * Return LinkProperties for the active (i.e., connected) default
575     * network interface.  It is assumed that at most one default network
576     * is active at a time. If more than one is active, it is indeterminate
577     * which will be returned.
578     * @return the ip properties for the active network, or {@code null} if
579     * none is active
580     */
581    public LinkProperties getActiveLinkProperties() {
582        enforceAccessPermission();
583        for (int type=0; type <= ConnectivityManager.MAX_NETWORK_TYPE; type++) {
584            if (mNetConfigs[type] == null || !mNetConfigs[type].isDefault()) {
585                continue;
586            }
587            NetworkStateTracker t = mNetTrackers[type];
588            NetworkInfo info = t.getNetworkInfo();
589            if (info.isConnected()) {
590                return t.getLinkProperties();
591            }
592        }
593        return null;
594    }
595
596    public LinkProperties getLinkProperties(int networkType) {
597        enforceAccessPermission();
598        if (ConnectivityManager.isNetworkTypeValid(networkType)) {
599            NetworkStateTracker t = mNetTrackers[networkType];
600            if (t != null) return t.getLinkProperties();
601        }
602        return null;
603    }
604
605    public boolean setRadios(boolean turnOn) {
606        boolean result = true;
607        enforceChangePermission();
608        for (NetworkStateTracker t : mNetTrackers) {
609            if (t != null) result = t.setRadio(turnOn) && result;
610        }
611        return result;
612    }
613
614    public boolean setRadio(int netType, boolean turnOn) {
615        enforceChangePermission();
616        if (!ConnectivityManager.isNetworkTypeValid(netType)) {
617            return false;
618        }
619        NetworkStateTracker tracker = mNetTrackers[netType];
620        return tracker != null && tracker.setRadio(turnOn);
621    }
622
623    /**
624     * Used to notice when the calling process dies so we can self-expire
625     *
626     * Also used to know if the process has cleaned up after itself when
627     * our auto-expire timer goes off.  The timer has a link to an object.
628     *
629     */
630    private class FeatureUser implements IBinder.DeathRecipient {
631        int mNetworkType;
632        String mFeature;
633        IBinder mBinder;
634        int mPid;
635        int mUid;
636        long mCreateTime;
637
638        FeatureUser(int type, String feature, IBinder binder) {
639            super();
640            mNetworkType = type;
641            mFeature = feature;
642            mBinder = binder;
643            mPid = getCallingPid();
644            mUid = getCallingUid();
645            mCreateTime = System.currentTimeMillis();
646
647            try {
648                mBinder.linkToDeath(this, 0);
649            } catch (RemoteException e) {
650                binderDied();
651            }
652        }
653
654        void unlinkDeathRecipient() {
655            mBinder.unlinkToDeath(this, 0);
656        }
657
658        public void binderDied() {
659            log("ConnectivityService FeatureUser binderDied(" +
660                    mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
661                    (System.currentTimeMillis() - mCreateTime) + " mSec ago");
662            stopUsingNetworkFeature(this, false);
663        }
664
665        public void expire() {
666            log("ConnectivityService FeatureUser expire(" +
667                    mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
668                    (System.currentTimeMillis() - mCreateTime) + " mSec ago");
669            stopUsingNetworkFeature(this, false);
670        }
671
672        public String toString() {
673            return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
674                    (System.currentTimeMillis() - mCreateTime) + " mSec ago";
675        }
676    }
677
678    // javadoc from interface
679    public int startUsingNetworkFeature(int networkType, String feature,
680            IBinder binder) {
681        if (DBG) {
682            log("startUsingNetworkFeature for net " + networkType + ": " + feature);
683        }
684        enforceChangePermission();
685        if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
686                mNetConfigs[networkType] == null) {
687            return Phone.APN_REQUEST_FAILED;
688        }
689
690        FeatureUser f = new FeatureUser(networkType, feature, binder);
691
692        // TODO - move this into the MobileDataStateTracker
693        int usedNetworkType = networkType;
694        if(networkType == ConnectivityManager.TYPE_MOBILE) {
695            usedNetworkType = convertFeatureToNetworkType(feature);
696            if (usedNetworkType < 0) {
697                Slog.e(TAG, "Can't match any netTracker!");
698                usedNetworkType = networkType;
699            }
700        }
701        NetworkStateTracker network = mNetTrackers[usedNetworkType];
702        if (network != null) {
703            Integer currentPid = new Integer(getCallingPid());
704            if (usedNetworkType != networkType) {
705                NetworkStateTracker radio = mNetTrackers[networkType];
706                NetworkInfo ni = network.getNetworkInfo();
707
708                if (ni.isAvailable() == false) {
709                    if (DBG) log("special network not available");
710                    if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
711                        return Phone.APN_TYPE_NOT_AVAILABLE;
712                    } else {
713                        // else make the attempt anyway - probably giving REQUEST_STARTED below
714                    }
715                }
716
717                synchronized(this) {
718                    mFeatureUsers.add(f);
719                    if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
720                        // this gets used for per-pid dns when connected
721                        mNetRequestersPids[usedNetworkType].add(currentPid);
722                    }
723                }
724
725                int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
726
727                if (restoreTimer >= 0) {
728                    mHandler.sendMessageDelayed(
729                            mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
730                }
731
732                if ((ni.isConnectedOrConnecting() == true) &&
733                        !network.isTeardownRequested()) {
734                    if (ni.isConnected() == true) {
735                        // add the pid-specific dns
736                        handleDnsConfigurationChange(networkType);
737                        if (DBG) log("special network already active");
738                        return Phone.APN_ALREADY_ACTIVE;
739                    }
740                    if (DBG) log("special network already connecting");
741                    return Phone.APN_REQUEST_STARTED;
742                }
743
744                // check if the radio in play can make another contact
745                // assume if cannot for now
746
747                if (DBG) log("reconnecting to special network");
748                network.reconnect();
749                return Phone.APN_REQUEST_STARTED;
750            } else {
751                // need to remember this unsupported request so we respond appropriately on stop
752                synchronized(this) {
753                    mFeatureUsers.add(f);
754                    if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
755                        // this gets used for per-pid dns when connected
756                        mNetRequestersPids[usedNetworkType].add(currentPid);
757                    }
758                }
759                return -1;
760            }
761        }
762        return Phone.APN_TYPE_NOT_AVAILABLE;
763    }
764
765    // javadoc from interface
766    public int stopUsingNetworkFeature(int networkType, String feature) {
767        enforceChangePermission();
768
769        int pid = getCallingPid();
770        int uid = getCallingUid();
771
772        FeatureUser u = null;
773        boolean found = false;
774
775        synchronized(this) {
776            for (int i = 0; i < mFeatureUsers.size() ; i++) {
777                u = (FeatureUser)mFeatureUsers.get(i);
778                if (uid == u.mUid && pid == u.mPid &&
779                        networkType == u.mNetworkType &&
780                        TextUtils.equals(feature, u.mFeature)) {
781                    found = true;
782                    break;
783                }
784            }
785        }
786        if (found && u != null) {
787            // stop regardless of how many other time this proc had called start
788            return stopUsingNetworkFeature(u, true);
789        } else {
790            // none found!
791            if (DBG) log("ignoring stopUsingNetworkFeature - not a live request");
792            return 1;
793        }
794    }
795
796    private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
797        int networkType = u.mNetworkType;
798        String feature = u.mFeature;
799        int pid = u.mPid;
800        int uid = u.mUid;
801
802        NetworkStateTracker tracker = null;
803        boolean callTeardown = false;  // used to carry our decision outside of sync block
804
805        if (DBG) {
806            log("stopUsingNetworkFeature for net " + networkType +
807                    ": " + feature);
808        }
809
810        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
811            return -1;
812        }
813
814        // need to link the mFeatureUsers list with the mNetRequestersPids state in this
815        // sync block
816        synchronized(this) {
817            // check if this process still has an outstanding start request
818            if (!mFeatureUsers.contains(u)) {
819                if (DBG) log("ignoring - this process has no outstanding requests");
820                return 1;
821            }
822            u.unlinkDeathRecipient();
823            mFeatureUsers.remove(mFeatureUsers.indexOf(u));
824            // If we care about duplicate requests, check for that here.
825            //
826            // This is done to support the extension of a request - the app
827            // can request we start the network feature again and renew the
828            // auto-shutoff delay.  Normal "stop" calls from the app though
829            // do not pay attention to duplicate requests - in effect the
830            // API does not refcount and a single stop will counter multiple starts.
831            if (ignoreDups == false) {
832                for (int i = 0; i < mFeatureUsers.size() ; i++) {
833                    FeatureUser x = (FeatureUser)mFeatureUsers.get(i);
834                    if (x.mUid == u.mUid && x.mPid == u.mPid &&
835                            x.mNetworkType == u.mNetworkType &&
836                            TextUtils.equals(x.mFeature, u.mFeature)) {
837                        if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
838                        return 1;
839                    }
840                }
841            }
842
843            // TODO - move to MobileDataStateTracker
844            int usedNetworkType = networkType;
845            if (networkType == ConnectivityManager.TYPE_MOBILE) {
846                usedNetworkType = convertFeatureToNetworkType(feature);
847                if (usedNetworkType < 0) {
848                    usedNetworkType = networkType;
849                }
850            }
851            tracker =  mNetTrackers[usedNetworkType];
852            if (tracker == null) {
853                if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
854                return -1;
855            }
856            if (usedNetworkType != networkType) {
857                Integer currentPid = new Integer(pid);
858                mNetRequestersPids[usedNetworkType].remove(currentPid);
859                reassessPidDns(pid, true);
860                if (mNetRequestersPids[usedNetworkType].size() != 0) {
861                    if (DBG) log("not tearing down special network - " +
862                           "others still using it");
863                    return 1;
864                }
865                callTeardown = true;
866            } else {
867                if (DBG) log("not a known feature - dropping");
868            }
869        }
870        if (DBG) log("Doing network teardown");
871        if (callTeardown) {
872            tracker.teardown();
873            return 1;
874        } else {
875            return -1;
876        }
877    }
878
879    /**
880     * @deprecated use requestRouteToHostAddress instead
881     *
882     * Ensure that a network route exists to deliver traffic to the specified
883     * host via the specified network interface.
884     * @param networkType the type of the network over which traffic to the
885     * specified host is to be routed
886     * @param hostAddress the IP address of the host to which the route is
887     * desired
888     * @return {@code true} on success, {@code false} on failure
889     */
890    public boolean requestRouteToHost(int networkType, int hostAddress) {
891        InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
892
893        if (inetAddress == null) {
894            return false;
895        }
896
897        return requestRouteToHostAddress(networkType, inetAddress.getAddress());
898    }
899
900    /**
901     * Ensure that a network route exists to deliver traffic to the specified
902     * host via the specified network interface.
903     * @param networkType the type of the network over which traffic to the
904     * specified host is to be routed
905     * @param hostAddress the IP address of the host to which the route is
906     * desired
907     * @return {@code true} on success, {@code false} on failure
908     */
909    public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
910        enforceChangePermission();
911        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
912            return false;
913        }
914        NetworkStateTracker tracker = mNetTrackers[networkType];
915
916        if (tracker == null || !tracker.getNetworkInfo().isConnected() ||
917                tracker.isTeardownRequested()) {
918            if (DBG) {
919                log("requestRouteToHostAddress on down network " +
920                           "(" + networkType + ") - dropped");
921            }
922            return false;
923        }
924        try {
925            InetAddress addr = InetAddress.getByAddress(hostAddress);
926            return addHostRoute(tracker, addr, 0);
927        } catch (UnknownHostException e) {}
928        return false;
929    }
930
931    /**
932     * Ensure that a network route exists to deliver traffic to the specified
933     * host via the mobile data network.
934     * @param hostAddress the IP address of the host to which the route is desired,
935     * in network byte order.
936     * TODO - deprecate
937     * @return {@code true} on success, {@code false} on failure
938     */
939    private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress, int cycleCount) {
940        LinkProperties lp = nt.getLinkProperties();
941        if ((lp == null) || (hostAddress == null)) return false;
942
943        String interfaceName = lp.getInterfaceName();
944        if (DBG) {
945            log("Requested host route to " + hostAddress + "(" + interfaceName + "), cycleCount=" +
946                    cycleCount);
947        }
948        if (interfaceName == null) {
949            if (DBG) loge("addHostRoute failed due to null interface name");
950            return false;
951        }
952
953        RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), hostAddress);
954        InetAddress gatewayAddress = null;
955        if (bestRoute != null) {
956            gatewayAddress = bestRoute.getGateway();
957            // if the best route is ourself, don't relf-reference, just add the host route
958            if (hostAddress.equals(gatewayAddress)) gatewayAddress = null;
959        }
960        if (gatewayAddress != null) {
961            if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
962                loge("Error adding hostroute - too much recursion");
963                return false;
964            }
965            if (!addHostRoute(nt, gatewayAddress, cycleCount+1)) return false;
966        }
967
968        RouteInfo route = RouteInfo.makeHostRoute(hostAddress, gatewayAddress);
969
970        try {
971            mNetd.addRoute(interfaceName, route);
972            return true;
973        } catch (Exception ex) {
974            return false;
975        }
976    }
977
978    // TODO support the removal of single host routes.  Keep a ref count of them so we
979    // aren't over-zealous
980    private boolean removeHostRoute(NetworkStateTracker nt, InetAddress hostAddress) {
981        return false;
982    }
983
984    /**
985     * @see ConnectivityManager#getBackgroundDataSetting()
986     */
987    public boolean getBackgroundDataSetting() {
988        return mBackgroundDataEnabled.get();
989    }
990
991    /**
992     * @see ConnectivityManager#setBackgroundDataSetting(boolean)
993     */
994    public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) {
995        mContext.enforceCallingOrSelfPermission(
996                android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING,
997                "ConnectivityService");
998
999        mBackgroundDataEnabled.set(allowBackgroundDataUsage);
1000
1001        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA,
1002                (allowBackgroundDataUsage ? ENABLED : DISABLED), 0));
1003    }
1004
1005    private void handleSetBackgroundData(boolean enabled) {
1006        Settings.Secure.putInt(mContext.getContentResolver(),
1007                Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0);
1008        Intent broadcast = new Intent(
1009                ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1010        mContext.sendBroadcast(broadcast);
1011    }
1012
1013    /**
1014     * @see ConnectivityManager#getMobileDataEnabled()
1015     */
1016    public boolean getMobileDataEnabled() {
1017        // TODO: This detail should probably be in DataConnectionTracker's
1018        //       which is where we store the value and maybe make this
1019        //       asynchronous.
1020        enforceAccessPermission();
1021        boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(),
1022                Settings.Secure.MOBILE_DATA, 1) == 1;
1023        if (DBG) log("getMobileDataEnabled returning " + retVal);
1024        return retVal;
1025    }
1026
1027    public void setDataDependency(int networkType, boolean met) {
1028        enforceChangePermission();
1029        if (DBG) {
1030            log("setDataDependency(" + networkType + ", " + met + ")");
1031        }
1032        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1033                (met ? ENABLED : DISABLED), networkType));
1034    }
1035
1036    private void handleSetDependencyMet(int networkType, boolean met) {
1037        if (mNetTrackers[networkType] != null) {
1038            if (DBG) {
1039                log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1040            }
1041            mNetTrackers[networkType].setDependencyMet(met);
1042        }
1043    }
1044
1045    /**
1046     * @see ConnectivityManager#setMobileDataEnabled(boolean)
1047     */
1048    public void setMobileDataEnabled(boolean enabled) {
1049        enforceChangePermission();
1050        if (DBG) log("setMobileDataEnabled(" + enabled + ")");
1051
1052        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
1053                (enabled ? ENABLED : DISABLED), 0));
1054    }
1055
1056    private void handleSetMobileData(boolean enabled) {
1057        if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1058            if (DBG) {
1059                Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
1060            }
1061            mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled);
1062        }
1063    }
1064
1065    private void enforceAccessPermission() {
1066        mContext.enforceCallingOrSelfPermission(
1067                android.Manifest.permission.ACCESS_NETWORK_STATE,
1068                "ConnectivityService");
1069    }
1070
1071    private void enforceChangePermission() {
1072        mContext.enforceCallingOrSelfPermission(
1073                android.Manifest.permission.CHANGE_NETWORK_STATE,
1074                "ConnectivityService");
1075    }
1076
1077    // TODO Make this a special check when it goes public
1078    private void enforceTetherChangePermission() {
1079        mContext.enforceCallingOrSelfPermission(
1080                android.Manifest.permission.CHANGE_NETWORK_STATE,
1081                "ConnectivityService");
1082    }
1083
1084    private void enforceTetherAccessPermission() {
1085        mContext.enforceCallingOrSelfPermission(
1086                android.Manifest.permission.ACCESS_NETWORK_STATE,
1087                "ConnectivityService");
1088    }
1089
1090    private void enforceConnectivityInternalPermission() {
1091        mContext.enforceCallingOrSelfPermission(
1092                android.Manifest.permission.CONNECTIVITY_INTERNAL,
1093                "ConnectivityService");
1094    }
1095
1096    /**
1097     * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1098     * network, we ignore it. If it is for the active network, we send out a
1099     * broadcast. But first, we check whether it might be possible to connect
1100     * to a different network.
1101     * @param info the {@code NetworkInfo} for the network
1102     */
1103    private void handleDisconnect(NetworkInfo info) {
1104
1105        int prevNetType = info.getType();
1106
1107        mNetTrackers[prevNetType].setTeardownRequested(false);
1108        /*
1109         * If the disconnected network is not the active one, then don't report
1110         * this as a loss of connectivity. What probably happened is that we're
1111         * getting the disconnect for a network that we explicitly disabled
1112         * in accordance with network preference policies.
1113         */
1114        if (!mNetConfigs[prevNetType].isDefault()) {
1115            List pids = mNetRequestersPids[prevNetType];
1116            for (int i = 0; i<pids.size(); i++) {
1117                Integer pid = (Integer)pids.get(i);
1118                // will remove them because the net's no longer connected
1119                // need to do this now as only now do we know the pids and
1120                // can properly null things that are no longer referenced.
1121                reassessPidDns(pid.intValue(), false);
1122            }
1123        }
1124
1125        Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1126        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1127        if (info.isFailover()) {
1128            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1129            info.setFailover(false);
1130        }
1131        if (info.getReason() != null) {
1132            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1133        }
1134        if (info.getExtraInfo() != null) {
1135            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1136                    info.getExtraInfo());
1137        }
1138
1139        if (mNetConfigs[prevNetType].isDefault()) {
1140            tryFailover(prevNetType);
1141            if (mActiveDefaultNetwork != -1) {
1142                NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1143                intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1144            } else {
1145                mDefaultInetConditionPublished = 0; // we're not connected anymore
1146                intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1147            }
1148        }
1149        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1150        // do this before we broadcast the change
1151        handleConnectivityChange(prevNetType);
1152
1153        sendStickyBroadcast(intent);
1154        /*
1155         * If the failover network is already connected, then immediately send
1156         * out a followup broadcast indicating successful failover
1157         */
1158        if (mActiveDefaultNetwork != -1) {
1159            sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
1160        }
1161    }
1162
1163    private void tryFailover(int prevNetType) {
1164        /*
1165         * If this is a default network, check if other defaults are available.
1166         * Try to reconnect on all available and let them hash it out when
1167         * more than one connects.
1168         */
1169        if (mNetConfigs[prevNetType].isDefault()) {
1170            if (mActiveDefaultNetwork == prevNetType) {
1171                mActiveDefaultNetwork = -1;
1172            }
1173
1174            // don't signal a reconnect for anything lower or equal priority than our
1175            // current connected default
1176            // TODO - don't filter by priority now - nice optimization but risky
1177//            int currentPriority = -1;
1178//            if (mActiveDefaultNetwork != -1) {
1179//                currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
1180//            }
1181            for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
1182                if (checkType == prevNetType) continue;
1183                if (mNetConfigs[checkType] == null) continue;
1184                if (!mNetConfigs[checkType].isDefault()) continue;
1185
1186// Enabling the isAvailable() optimization caused mobile to not get
1187// selected if it was in the middle of error handling. Specifically
1188// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1189// would not be available and we wouldn't get connected to anything.
1190// So removing the isAvailable() optimization below for now. TODO: This
1191// optimization should work and we need to investigate why it doesn't work.
1192// This could be related to how DEACTIVATE_DATA_CALL is reporting its
1193// complete before it is really complete.
1194//                if (!mNetTrackers[checkType].isAvailable()) continue;
1195
1196//                if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
1197
1198                NetworkStateTracker checkTracker = mNetTrackers[checkType];
1199                NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1200                if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1201                    checkInfo.setFailover(true);
1202                    checkTracker.reconnect();
1203                }
1204                if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
1205            }
1206        }
1207    }
1208
1209    private void sendConnectedBroadcast(NetworkInfo info) {
1210        sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION);
1211    }
1212
1213    private void sendInetConditionBroadcast(NetworkInfo info) {
1214        sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1215    }
1216
1217    private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1218        Intent intent = new Intent(bcastType);
1219        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1220        if (info.isFailover()) {
1221            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1222            info.setFailover(false);
1223        }
1224        if (info.getReason() != null) {
1225            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1226        }
1227        if (info.getExtraInfo() != null) {
1228            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1229                    info.getExtraInfo());
1230        }
1231        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1232        sendStickyBroadcast(intent);
1233    }
1234
1235    /**
1236     * Called when an attempt to fail over to another network has failed.
1237     * @param info the {@link NetworkInfo} for the failed network
1238     */
1239    private void handleConnectionFailure(NetworkInfo info) {
1240        mNetTrackers[info.getType()].setTeardownRequested(false);
1241
1242        String reason = info.getReason();
1243        String extraInfo = info.getExtraInfo();
1244
1245        String reasonText;
1246        if (reason == null) {
1247            reasonText = ".";
1248        } else {
1249            reasonText = " (" + reason + ").";
1250        }
1251        loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
1252
1253        Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1254        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
1255        if (getActiveNetworkInfo() == null) {
1256            intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1257        }
1258        if (reason != null) {
1259            intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1260        }
1261        if (extraInfo != null) {
1262            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1263        }
1264        if (info.isFailover()) {
1265            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1266            info.setFailover(false);
1267        }
1268
1269        if (mNetConfigs[info.getType()].isDefault()) {
1270            tryFailover(info.getType());
1271            if (mActiveDefaultNetwork != -1) {
1272                NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1273                intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1274            } else {
1275                mDefaultInetConditionPublished = 0;
1276                intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1277            }
1278        }
1279
1280        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1281        sendStickyBroadcast(intent);
1282        /*
1283         * If the failover network is already connected, then immediately send
1284         * out a followup broadcast indicating successful failover
1285         */
1286        if (mActiveDefaultNetwork != -1) {
1287            sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
1288        }
1289    }
1290
1291    private void sendStickyBroadcast(Intent intent) {
1292        synchronized(this) {
1293            if (!mSystemReady) {
1294                mInitialBroadcast = new Intent(intent);
1295            }
1296            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1297            mContext.sendStickyBroadcast(intent);
1298        }
1299    }
1300
1301    void systemReady() {
1302        IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
1303        mNetd = INetworkManagementService.Stub.asInterface(b);
1304
1305        synchronized(this) {
1306            mSystemReady = true;
1307            if (mInitialBroadcast != null) {
1308                mContext.sendStickyBroadcast(mInitialBroadcast);
1309                mInitialBroadcast = null;
1310            }
1311        }
1312        // load the global proxy at startup
1313        mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
1314    }
1315
1316    private void handleConnect(NetworkInfo info) {
1317        int type = info.getType();
1318
1319        // snapshot isFailover, because sendConnectedBroadcast() resets it
1320        boolean isFailover = info.isFailover();
1321        NetworkStateTracker thisNet = mNetTrackers[type];
1322
1323        // if this is a default net and other default is running
1324        // kill the one not preferred
1325        if (mNetConfigs[type].isDefault()) {
1326            if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
1327                if ((type != mNetworkPreference &&
1328                        mNetConfigs[mActiveDefaultNetwork].priority >
1329                        mNetConfigs[type].priority) ||
1330                        mNetworkPreference == mActiveDefaultNetwork) {
1331                        // don't accept this one
1332                        if (DBG) {
1333                            log("Not broadcasting CONNECT_ACTION " +
1334                                "to torn down network " + info.getTypeName());
1335                        }
1336                        teardown(thisNet);
1337                        return;
1338                } else {
1339                    // tear down the other
1340                    NetworkStateTracker otherNet =
1341                            mNetTrackers[mActiveDefaultNetwork];
1342                    if (DBG) {
1343                        log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
1344                            " teardown");
1345                    }
1346                    if (!teardown(otherNet)) {
1347                        loge("Network declined teardown request");
1348                        teardown(thisNet);
1349                        return;
1350                    }
1351                }
1352            }
1353            synchronized (ConnectivityService.this) {
1354                // have a new default network, release the transition wakelock in a second
1355                // if it's held.  The second pause is to allow apps to reconnect over the
1356                // new network
1357                if (mNetTransitionWakeLock.isHeld()) {
1358                    mHandler.sendMessageDelayed(mHandler.obtainMessage(
1359                            EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
1360                            mNetTransitionWakeLockSerialNumber, 0),
1361                            1000);
1362                }
1363            }
1364            mActiveDefaultNetwork = type;
1365            // this will cause us to come up initially as unconnected and switching
1366            // to connected after our normal pause unless somebody reports us as reall
1367            // disconnected
1368            mDefaultInetConditionPublished = 0;
1369            mDefaultConnectionSequence++;
1370            mInetConditionChangeInFlight = false;
1371            // Don't do this - if we never sign in stay, grey
1372            //reportNetworkCondition(mActiveDefaultNetwork, 100);
1373        }
1374        thisNet.setTeardownRequested(false);
1375        updateNetworkSettings(thisNet);
1376        handleConnectivityChange(type);
1377        sendConnectedBroadcast(info);
1378    }
1379
1380    /**
1381     * After a change in the connectivity state of a network. We're mainly
1382     * concerned with making sure that the list of DNS servers is set up
1383     * according to which networks are connected, and ensuring that the
1384     * right routing table entries exist.
1385     */
1386    private void handleConnectivityChange(int netType) {
1387        /*
1388         * If a non-default network is enabled, add the host routes that
1389         * will allow it's DNS servers to be accessed.
1390         */
1391        handleDnsConfigurationChange(netType);
1392
1393        if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
1394            if (mNetConfigs[netType].isDefault()) {
1395                handleApplyDefaultProxy(netType);
1396                addDefaultRoute(mNetTrackers[netType]);
1397            } else {
1398                // many radios add a default route even when we don't want one.
1399                // remove the default route unless we need it for our active network
1400                if (mActiveDefaultNetwork != -1) {
1401                    LinkProperties defaultLinkProperties =
1402                            mNetTrackers[mActiveDefaultNetwork].getLinkProperties();
1403                    LinkProperties newLinkProperties =
1404                            mNetTrackers[netType].getLinkProperties();
1405                    String defaultIface = defaultLinkProperties.getInterfaceName();
1406                    if (defaultIface != null &&
1407                            !defaultIface.equals(newLinkProperties.getInterfaceName())) {
1408                        removeDefaultRoute(mNetTrackers[netType]);
1409                    }
1410                }
1411                addPrivateDnsRoutes(mNetTrackers[netType]);
1412            }
1413
1414            /** Notify TetheringService if interface name has been changed. */
1415            if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
1416                                 Phone.REASON_LINK_PROPERTIES_CHANGED)) {
1417                handleTetherIfaceChange(netType);
1418            }
1419        } else {
1420            if (mNetConfigs[netType].isDefault()) {
1421                removeDefaultRoute(mNetTrackers[netType]);
1422            } else {
1423                removePrivateDnsRoutes(mNetTrackers[netType]);
1424            }
1425        }
1426    }
1427
1428    private void addPrivateDnsRoutes(NetworkStateTracker nt) {
1429        boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1430        LinkProperties p = nt.getLinkProperties();
1431        if (p == null) return;
1432        String interfaceName = p.getInterfaceName();
1433
1434        if (DBG) {
1435            log("addPrivateDnsRoutes for " + nt +
1436                    "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet);
1437        }
1438        if (interfaceName != null && !privateDnsRouteSet) {
1439            Collection<InetAddress> dnsList = p.getDnses();
1440            for (InetAddress dns : dnsList) {
1441                addHostRoute(nt, dns, 0);
1442            }
1443            nt.privateDnsRouteSet(true);
1444        }
1445    }
1446
1447    private void removePrivateDnsRoutes(NetworkStateTracker nt) {
1448        LinkProperties p = nt.getLinkProperties();
1449        if (p == null) return;
1450        String interfaceName = p.getInterfaceName();
1451        boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet();
1452        if (interfaceName != null && privateDnsRouteSet) {
1453            if (DBG) {
1454                log("removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() +
1455                        " (" + interfaceName + ")");
1456            }
1457
1458            Collection<InetAddress> dnsList = p.getDnses();
1459            for (InetAddress dns : dnsList) {
1460                if (DBG) log("  removing " + dns);
1461                RouteInfo route = RouteInfo.makeHostRoute(dns);
1462                try {
1463                    mNetd.removeRoute(interfaceName, route);
1464                } catch (Exception ex) {
1465                    loge("error (" + ex + ") removing dns route " + route);
1466                }
1467            }
1468            nt.privateDnsRouteSet(false);
1469        }
1470    }
1471
1472
1473    private void addDefaultRoute(NetworkStateTracker nt) {
1474        LinkProperties p = nt.getLinkProperties();
1475        if (p == null) return;
1476        String interfaceName = p.getInterfaceName();
1477        if (TextUtils.isEmpty(interfaceName)) return;
1478
1479        for (RouteInfo route : p.getRoutes()) {
1480            //TODO - handle non-default routes
1481            if (route.isDefaultRoute()) {
1482                if (DBG) log("adding default route " + route);
1483                InetAddress gateway = route.getGateway();
1484                if (addHostRoute(nt, gateway, 0)) {
1485                    try {
1486                        mNetd.addRoute(interfaceName, route);
1487                    } catch (Exception e) {
1488                        loge("error adding default route " + route);
1489                        continue;
1490                    }
1491                    if (DBG) {
1492                        NetworkInfo networkInfo = nt.getNetworkInfo();
1493                        log("addDefaultRoute for " + networkInfo.getTypeName() +
1494                                " (" + interfaceName + "), GatewayAddr=" +
1495                                gateway.getHostAddress());
1496                    }
1497                } else {
1498                    loge("error adding host route for default route " + route);
1499                }
1500            }
1501        }
1502    }
1503
1504
1505    public void removeDefaultRoute(NetworkStateTracker nt) {
1506        LinkProperties p = nt.getLinkProperties();
1507        if (p == null) return;
1508        String interfaceName = p.getInterfaceName();
1509
1510        if (interfaceName == null) return;
1511
1512        for (RouteInfo route : p.getRoutes()) {
1513            //TODO - handle non-default routes
1514            if (route.isDefaultRoute()) {
1515                try {
1516                    mNetd.removeRoute(interfaceName, route);
1517                } catch (Exception ex) {
1518                    loge("error (" + ex + ") removing default route " + route);
1519                    continue;
1520                }
1521                if (DBG) {
1522                    NetworkInfo networkInfo = nt.getNetworkInfo();
1523                    log("removeDefaultRoute for " + networkInfo.getTypeName() + " (" +
1524                            interfaceName + ")");
1525                }
1526            }
1527        }
1528    }
1529
1530   /**
1531     * Reads the network specific TCP buffer sizes from SystemProperties
1532     * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
1533     * wide use
1534     */
1535   public void updateNetworkSettings(NetworkStateTracker nt) {
1536        String key = nt.getTcpBufferSizesPropName();
1537        String bufferSizes = SystemProperties.get(key);
1538
1539        if (bufferSizes.length() == 0) {
1540            loge(key + " not found in system properties. Using defaults");
1541
1542            // Setting to default values so we won't be stuck to previous values
1543            key = "net.tcp.buffersize.default";
1544            bufferSizes = SystemProperties.get(key);
1545        }
1546
1547        // Set values in kernel
1548        if (bufferSizes.length() != 0) {
1549            if (DBG) {
1550                log("Setting TCP values: [" + bufferSizes
1551                        + "] which comes from [" + key + "]");
1552            }
1553            setBufferSize(bufferSizes);
1554        }
1555    }
1556
1557   /**
1558     * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
1559     * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
1560     *
1561     * @param bufferSizes in the format of "readMin, readInitial, readMax,
1562     *        writeMin, writeInitial, writeMax"
1563     */
1564    private void setBufferSize(String bufferSizes) {
1565        try {
1566            String[] values = bufferSizes.split(",");
1567
1568            if (values.length == 6) {
1569              final String prefix = "/sys/kernel/ipv4/tcp_";
1570                stringToFile(prefix + "rmem_min", values[0]);
1571                stringToFile(prefix + "rmem_def", values[1]);
1572                stringToFile(prefix + "rmem_max", values[2]);
1573                stringToFile(prefix + "wmem_min", values[3]);
1574                stringToFile(prefix + "wmem_def", values[4]);
1575                stringToFile(prefix + "wmem_max", values[5]);
1576            } else {
1577                loge("Invalid buffersize string: " + bufferSizes);
1578            }
1579        } catch (IOException e) {
1580            loge("Can't set tcp buffer sizes:" + e);
1581        }
1582    }
1583
1584   /**
1585     * Writes string to file. Basically same as "echo -n $string > $filename"
1586     *
1587     * @param filename
1588     * @param string
1589     * @throws IOException
1590     */
1591    private void stringToFile(String filename, String string) throws IOException {
1592        FileWriter out = new FileWriter(filename);
1593        try {
1594            out.write(string);
1595        } finally {
1596            out.close();
1597        }
1598    }
1599
1600
1601    /**
1602     * Adjust the per-process dns entries (net.dns<x>.<pid>) based
1603     * on the highest priority active net which this process requested.
1604     * If there aren't any, clear it out
1605     */
1606    private void reassessPidDns(int myPid, boolean doBump)
1607    {
1608        if (DBG) log("reassessPidDns for pid " + myPid);
1609        for(int i : mPriorityList) {
1610            if (mNetConfigs[i].isDefault()) {
1611                continue;
1612            }
1613            NetworkStateTracker nt = mNetTrackers[i];
1614            if (nt.getNetworkInfo().isConnected() &&
1615                    !nt.isTeardownRequested()) {
1616                LinkProperties p = nt.getLinkProperties();
1617                if (p == null) continue;
1618                List pids = mNetRequestersPids[i];
1619                for (int j=0; j<pids.size(); j++) {
1620                    Integer pid = (Integer)pids.get(j);
1621                    if (pid.intValue() == myPid) {
1622                        Collection<InetAddress> dnses = p.getDnses();
1623                        writePidDns(dnses, myPid);
1624                        if (doBump) {
1625                            bumpDns();
1626                        }
1627                        return;
1628                    }
1629                }
1630           }
1631        }
1632        // nothing found - delete
1633        for (int i = 1; ; i++) {
1634            String prop = "net.dns" + i + "." + myPid;
1635            if (SystemProperties.get(prop).length() == 0) {
1636                if (doBump) {
1637                    bumpDns();
1638                }
1639                return;
1640            }
1641            SystemProperties.set(prop, "");
1642        }
1643    }
1644
1645    // return true if results in a change
1646    private boolean writePidDns(Collection <InetAddress> dnses, int pid) {
1647        int j = 1;
1648        boolean changed = false;
1649        for (InetAddress dns : dnses) {
1650            String dnsString = dns.getHostAddress();
1651            if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) {
1652                changed = true;
1653                SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress());
1654            }
1655        }
1656        return changed;
1657    }
1658
1659    private void bumpDns() {
1660        /*
1661         * Bump the property that tells the name resolver library to reread
1662         * the DNS server list from the properties.
1663         */
1664        String propVal = SystemProperties.get("net.dnschange");
1665        int n = 0;
1666        if (propVal.length() != 0) {
1667            try {
1668                n = Integer.parseInt(propVal);
1669            } catch (NumberFormatException e) {}
1670        }
1671        SystemProperties.set("net.dnschange", "" + (n+1));
1672        /*
1673         * Tell the VMs to toss their DNS caches
1674         */
1675        Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1676        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1677        /*
1678         * Connectivity events can happen before boot has completed ...
1679         */
1680        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1681        mContext.sendBroadcast(intent);
1682    }
1683
1684    private void handleDnsConfigurationChange(int netType) {
1685        // add default net's dns entries
1686        NetworkStateTracker nt = mNetTrackers[netType];
1687        if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
1688            LinkProperties p = nt.getLinkProperties();
1689            if (p == null) return;
1690            Collection<InetAddress> dnses = p.getDnses();
1691            boolean changed = false;
1692            if (mNetConfigs[netType].isDefault()) {
1693                int j = 1;
1694                if (dnses.size() == 0 && mDefaultDns != null) {
1695                    String dnsString = mDefaultDns.getHostAddress();
1696                    if (!dnsString.equals(SystemProperties.get("net.dns1"))) {
1697                        if (DBG) {
1698                            log("no dns provided - using " + dnsString);
1699                        }
1700                        changed = true;
1701                        SystemProperties.set("net.dns1", dnsString);
1702                    }
1703                    j++;
1704                } else {
1705                    for (InetAddress dns : dnses) {
1706                        String dnsString = dns.getHostAddress();
1707                        if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) {
1708                            j++;
1709                            continue;
1710                        }
1711                        if (DBG) {
1712                            log("adding dns " + dns + " for " +
1713                                    nt.getNetworkInfo().getTypeName());
1714                        }
1715                        changed = true;
1716                        SystemProperties.set("net.dns" + j++, dnsString);
1717                    }
1718                }
1719                for (int k=j ; k<mNumDnsEntries; k++) {
1720                    if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) {
1721                        if (DBG) log("erasing net.dns" + k);
1722                        changed = true;
1723                        SystemProperties.set("net.dns" + k, "");
1724                    }
1725                }
1726                mNumDnsEntries = j;
1727            } else {
1728                // set per-pid dns for attached secondary nets
1729                List pids = mNetRequestersPids[netType];
1730                for (int y=0; y< pids.size(); y++) {
1731                    Integer pid = (Integer)pids.get(y);
1732                    changed = writePidDns(dnses, pid.intValue());
1733                }
1734            }
1735            if (changed) bumpDns();
1736        }
1737    }
1738
1739    private int getRestoreDefaultNetworkDelay(int networkType) {
1740        String restoreDefaultNetworkDelayStr = SystemProperties.get(
1741                NETWORK_RESTORE_DELAY_PROP_NAME);
1742        if(restoreDefaultNetworkDelayStr != null &&
1743                restoreDefaultNetworkDelayStr.length() != 0) {
1744            try {
1745                return Integer.valueOf(restoreDefaultNetworkDelayStr);
1746            } catch (NumberFormatException e) {
1747            }
1748        }
1749        // if the system property isn't set, use the value for the apn type
1750        int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1751
1752        if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1753                (mNetConfigs[networkType] != null)) {
1754            ret = mNetConfigs[networkType].restoreTime;
1755        }
1756        return ret;
1757    }
1758
1759    @Override
1760    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1761        if (mContext.checkCallingOrSelfPermission(
1762                android.Manifest.permission.DUMP)
1763                != PackageManager.PERMISSION_GRANTED) {
1764            pw.println("Permission Denial: can't dump ConnectivityService " +
1765                    "from from pid=" + Binder.getCallingPid() + ", uid=" +
1766                    Binder.getCallingUid());
1767            return;
1768        }
1769        pw.println();
1770        for (NetworkStateTracker nst : mNetTrackers) {
1771            if (nst != null) {
1772                if (nst.getNetworkInfo().isConnected()) {
1773                    pw.println("Active network: " + nst.getNetworkInfo().
1774                            getTypeName());
1775                }
1776                pw.println(nst.getNetworkInfo());
1777                pw.println(nst);
1778                pw.println();
1779            }
1780        }
1781
1782        pw.println("Network Requester Pids:");
1783        for (int net : mPriorityList) {
1784            String pidString = net + ": ";
1785            for (Object pid : mNetRequestersPids[net]) {
1786                pidString = pidString + pid.toString() + ", ";
1787            }
1788            pw.println(pidString);
1789        }
1790        pw.println();
1791
1792        pw.println("FeatureUsers:");
1793        for (Object requester : mFeatureUsers) {
1794            pw.println(requester.toString());
1795        }
1796        pw.println();
1797
1798        synchronized (this) {
1799            pw.println("NetworkTranstionWakeLock is currently " +
1800                    (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1801            pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1802        }
1803        pw.println();
1804
1805        mTethering.dump(fd, pw, args);
1806
1807        if (mInetLog != null) {
1808            pw.println();
1809            pw.println("Inet condition reports:");
1810            for(int i = 0; i < mInetLog.size(); i++) {
1811                pw.println(mInetLog.get(i));
1812            }
1813        }
1814    }
1815
1816    // must be stateless - things change under us.
1817    private class MyHandler extends Handler {
1818        public MyHandler(Looper looper) {
1819            super(looper);
1820        }
1821
1822        @Override
1823        public void handleMessage(Message msg) {
1824            NetworkInfo info;
1825            switch (msg.what) {
1826                case NetworkStateTracker.EVENT_STATE_CHANGED:
1827                    info = (NetworkInfo) msg.obj;
1828                    int type = info.getType();
1829                    NetworkInfo.State state = info.getState();
1830
1831                    if (DBG) log("ConnectivityChange for " +
1832                            info.getTypeName() + ": " +
1833                            state + "/" + info.getDetailedState());
1834
1835                    // Connectivity state changed:
1836                    // [31-13] Reserved for future use
1837                    // [12-9] Network subtype (for mobile network, as defined
1838                    //         by TelephonyManager)
1839                    // [8-3] Detailed state ordinal (as defined by
1840                    //         NetworkInfo.DetailedState)
1841                    // [2-0] Network type (as defined by ConnectivityManager)
1842                    int eventLogParam = (info.getType() & 0x7) |
1843                            ((info.getDetailedState().ordinal() & 0x3f) << 3) |
1844                            (info.getSubtype() << 9);
1845                    EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED,
1846                            eventLogParam);
1847
1848                    if (info.getDetailedState() ==
1849                            NetworkInfo.DetailedState.FAILED) {
1850                        handleConnectionFailure(info);
1851                    } else if (state == NetworkInfo.State.DISCONNECTED) {
1852                        handleDisconnect(info);
1853                    } else if (state == NetworkInfo.State.SUSPENDED) {
1854                        // TODO: need to think this over.
1855                        // the logic here is, handle SUSPENDED the same as
1856                        // DISCONNECTED. The only difference being we are
1857                        // broadcasting an intent with NetworkInfo that's
1858                        // suspended. This allows the applications an
1859                        // opportunity to handle DISCONNECTED and SUSPENDED
1860                        // differently, or not.
1861                        handleDisconnect(info);
1862                    } else if (state == NetworkInfo.State.CONNECTED) {
1863                        handleConnect(info);
1864                    }
1865                    break;
1866                case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
1867                    info = (NetworkInfo) msg.obj;
1868                    handleConnectivityChange(info.getType());
1869                    break;
1870                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
1871                    String causedBy = null;
1872                    synchronized (ConnectivityService.this) {
1873                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
1874                                mNetTransitionWakeLock.isHeld()) {
1875                            mNetTransitionWakeLock.release();
1876                            causedBy = mNetTransitionWakeLockCausedBy;
1877                        }
1878                    }
1879                    if (causedBy != null) {
1880                        log("NetTransition Wakelock for " + causedBy + " released by timeout");
1881                    }
1882                    break;
1883                case EVENT_RESTORE_DEFAULT_NETWORK:
1884                    FeatureUser u = (FeatureUser)msg.obj;
1885                    u.expire();
1886                    break;
1887                case EVENT_INET_CONDITION_CHANGE:
1888                {
1889                    int netType = msg.arg1;
1890                    int condition = msg.arg2;
1891                    handleInetConditionChange(netType, condition);
1892                    break;
1893                }
1894                case EVENT_INET_CONDITION_HOLD_END:
1895                {
1896                    int netType = msg.arg1;
1897                    int sequence = msg.arg2;
1898                    handleInetConditionHoldEnd(netType, sequence);
1899                    break;
1900                }
1901                case EVENT_SET_NETWORK_PREFERENCE:
1902                {
1903                    int preference = msg.arg1;
1904                    handleSetNetworkPreference(preference);
1905                    break;
1906                }
1907                case EVENT_SET_BACKGROUND_DATA:
1908                {
1909                    boolean enabled = (msg.arg1 == ENABLED);
1910                    handleSetBackgroundData(enabled);
1911                    break;
1912                }
1913                case EVENT_SET_MOBILE_DATA:
1914                {
1915                    boolean enabled = (msg.arg1 == ENABLED);
1916                    handleSetMobileData(enabled);
1917                    break;
1918                }
1919                case EVENT_APPLY_GLOBAL_HTTP_PROXY:
1920                {
1921                    handleDeprecatedGlobalHttpProxy();
1922                    break;
1923                }
1924                case EVENT_SET_DEPENDENCY_MET:
1925                {
1926                    boolean met = (msg.arg1 == ENABLED);
1927                    handleSetDependencyMet(msg.arg2, met);
1928                    break;
1929                }
1930            }
1931        }
1932    }
1933
1934    // javadoc from interface
1935    public int tether(String iface) {
1936        enforceTetherChangePermission();
1937
1938        if (isTetheringSupported()) {
1939            return mTethering.tether(iface);
1940        } else {
1941            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1942        }
1943    }
1944
1945    // javadoc from interface
1946    public int untether(String iface) {
1947        enforceTetherChangePermission();
1948
1949        if (isTetheringSupported()) {
1950            return mTethering.untether(iface);
1951        } else {
1952            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1953        }
1954    }
1955
1956    // javadoc from interface
1957    public int getLastTetherError(String iface) {
1958        enforceTetherAccessPermission();
1959
1960        if (isTetheringSupported()) {
1961            return mTethering.getLastTetherError(iface);
1962        } else {
1963            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
1964        }
1965    }
1966
1967    // TODO - proper iface API for selection by property, inspection, etc
1968    public String[] getTetherableUsbRegexs() {
1969        enforceTetherAccessPermission();
1970        if (isTetheringSupported()) {
1971            return mTethering.getTetherableUsbRegexs();
1972        } else {
1973            return new String[0];
1974        }
1975    }
1976
1977    public String[] getTetherableWifiRegexs() {
1978        enforceTetherAccessPermission();
1979        if (isTetheringSupported()) {
1980            return mTethering.getTetherableWifiRegexs();
1981        } else {
1982            return new String[0];
1983        }
1984    }
1985
1986    public String[] getTetherableBluetoothRegexs() {
1987        enforceTetherAccessPermission();
1988        if (isTetheringSupported()) {
1989            return mTethering.getTetherableBluetoothRegexs();
1990        } else {
1991            return new String[0];
1992        }
1993    }
1994
1995    // TODO - move iface listing, queries, etc to new module
1996    // javadoc from interface
1997    public String[] getTetherableIfaces() {
1998        enforceTetherAccessPermission();
1999        return mTethering.getTetherableIfaces();
2000    }
2001
2002    public String[] getTetheredIfaces() {
2003        enforceTetherAccessPermission();
2004        return mTethering.getTetheredIfaces();
2005    }
2006
2007    public String[] getTetheringErroredIfaces() {
2008        enforceTetherAccessPermission();
2009        return mTethering.getErroredIfaces();
2010    }
2011
2012    // if ro.tether.denied = true we default to no tethering
2013    // gservices could set the secure setting to 1 though to enable it on a build where it
2014    // had previously been turned off.
2015    public boolean isTetheringSupported() {
2016        enforceTetherAccessPermission();
2017        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2018        boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(),
2019                Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0);
2020        return tetherEnabledInSettings && mTetheringConfigValid;
2021    }
2022
2023    // An API NetworkStateTrackers can call when they lose their network.
2024    // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2025    // whichever happens first.  The timer is started by the first caller and not
2026    // restarted by subsequent callers.
2027    public void requestNetworkTransitionWakelock(String forWhom) {
2028        enforceConnectivityInternalPermission();
2029        synchronized (this) {
2030            if (mNetTransitionWakeLock.isHeld()) return;
2031            mNetTransitionWakeLockSerialNumber++;
2032            mNetTransitionWakeLock.acquire();
2033            mNetTransitionWakeLockCausedBy = forWhom;
2034        }
2035        mHandler.sendMessageDelayed(mHandler.obtainMessage(
2036                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2037                mNetTransitionWakeLockSerialNumber, 0),
2038                mNetTransitionWakeLockTimeout);
2039        return;
2040    }
2041
2042    // 100 percent is full good, 0 is full bad.
2043    public void reportInetCondition(int networkType, int percentage) {
2044        if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
2045        mContext.enforceCallingOrSelfPermission(
2046                android.Manifest.permission.STATUS_BAR,
2047                "ConnectivityService");
2048
2049        if (DBG) {
2050            int pid = getCallingPid();
2051            int uid = getCallingUid();
2052            String s = pid + "(" + uid + ") reports inet is " +
2053                (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2054                "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2055            mInetLog.add(s);
2056            while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2057                mInetLog.remove(0);
2058            }
2059        }
2060        mHandler.sendMessage(mHandler.obtainMessage(
2061            EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2062    }
2063
2064    private void handleInetConditionChange(int netType, int condition) {
2065        if (DBG) {
2066            log("Inet connectivity change, net=" +
2067                    netType + ", condition=" + condition +
2068                    ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2069        }
2070        if (mActiveDefaultNetwork == -1) {
2071            if (DBG) log("no active default network - aborting");
2072            return;
2073        }
2074        if (mActiveDefaultNetwork != netType) {
2075            if (DBG) log("given net not default - aborting");
2076            return;
2077        }
2078        mDefaultInetCondition = condition;
2079        int delay;
2080        if (mInetConditionChangeInFlight == false) {
2081            if (DBG) log("starting a change hold");
2082            // setup a new hold to debounce this
2083            if (mDefaultInetCondition > 50) {
2084                delay = Settings.Secure.getInt(mContext.getContentResolver(),
2085                        Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2086            } else {
2087                delay = Settings.Secure.getInt(mContext.getContentResolver(),
2088                Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
2089            }
2090            mInetConditionChangeInFlight = true;
2091            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
2092                    mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
2093        } else {
2094            // we've set the new condition, when this hold ends that will get
2095            // picked up
2096            if (DBG) log("currently in hold - not setting new end evt");
2097        }
2098    }
2099
2100    private void handleInetConditionHoldEnd(int netType, int sequence) {
2101        if (DBG) {
2102            log("Inet hold end, net=" + netType +
2103                    ", condition =" + mDefaultInetCondition +
2104                    ", published condition =" + mDefaultInetConditionPublished);
2105        }
2106        mInetConditionChangeInFlight = false;
2107
2108        if (mActiveDefaultNetwork == -1) {
2109            if (DBG) log("no active default network - aborting");
2110            return;
2111        }
2112        if (mDefaultConnectionSequence != sequence) {
2113            if (DBG) log("event hold for obsolete network - aborting");
2114            return;
2115        }
2116        if (mDefaultInetConditionPublished == mDefaultInetCondition) {
2117            if (DBG) log("no change in condition - aborting");
2118            return;
2119        }
2120        NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
2121        if (networkInfo.isConnected() == false) {
2122            if (DBG) log("default network not connected - aborting");
2123            return;
2124        }
2125        mDefaultInetConditionPublished = mDefaultInetCondition;
2126        sendInetConditionBroadcast(networkInfo);
2127        return;
2128    }
2129
2130    public synchronized ProxyProperties getProxy() {
2131        if (mGlobalProxy != null) return mGlobalProxy;
2132        if (mDefaultProxy != null) return mDefaultProxy;
2133        return null;
2134    }
2135
2136    public void setGlobalProxy(ProxyProperties proxyProperties) {
2137        enforceChangePermission();
2138        synchronized (mGlobalProxyLock) {
2139            if (proxyProperties == mGlobalProxy) return;
2140            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2141            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2142
2143            String host = "";
2144            int port = 0;
2145            String exclList = "";
2146            if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
2147                mGlobalProxy = new ProxyProperties(proxyProperties);
2148                host = mGlobalProxy.getHost();
2149                port = mGlobalProxy.getPort();
2150                exclList = mGlobalProxy.getExclusionList();
2151            } else {
2152                mGlobalProxy = null;
2153            }
2154            ContentResolver res = mContext.getContentResolver();
2155            Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host);
2156            Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port);
2157            Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2158                    exclList);
2159        }
2160
2161        if (mGlobalProxy == null) {
2162            proxyProperties = mDefaultProxy;
2163        }
2164        sendProxyBroadcast(proxyProperties);
2165    }
2166
2167    private void loadGlobalProxy() {
2168        ContentResolver res = mContext.getContentResolver();
2169        String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST);
2170        int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0);
2171        String exclList = Settings.Secure.getString(res,
2172                Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2173        if (!TextUtils.isEmpty(host)) {
2174            ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
2175            synchronized (mGlobalProxyLock) {
2176                mGlobalProxy = proxyProperties;
2177            }
2178        }
2179    }
2180
2181    public ProxyProperties getGlobalProxy() {
2182        synchronized (mGlobalProxyLock) {
2183            return mGlobalProxy;
2184        }
2185    }
2186
2187    private void handleApplyDefaultProxy(int type) {
2188        // check if new default - push it out to all VM if so
2189        ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy();
2190        synchronized (this) {
2191            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2192            if (mDefaultProxy == proxy) return;
2193            if (!TextUtils.isEmpty(proxy.getHost())) {
2194                mDefaultProxy = proxy;
2195            } else {
2196                mDefaultProxy = null;
2197            }
2198        }
2199        if (DBG) log("changing default proxy to " + proxy);
2200        if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
2201        if (mGlobalProxy != null) return;
2202        sendProxyBroadcast(proxy);
2203    }
2204
2205    private void handleDeprecatedGlobalHttpProxy() {
2206        String proxy = Settings.Secure.getString(mContext.getContentResolver(),
2207                Settings.Secure.HTTP_PROXY);
2208        if (!TextUtils.isEmpty(proxy)) {
2209            String data[] = proxy.split(":");
2210            String proxyHost =  data[0];
2211            int proxyPort = 8080;
2212            if (data.length > 1) {
2213                try {
2214                    proxyPort = Integer.parseInt(data[1]);
2215                } catch (NumberFormatException e) {
2216                    return;
2217                }
2218            }
2219            ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
2220            setGlobalProxy(p);
2221        }
2222    }
2223
2224    private void sendProxyBroadcast(ProxyProperties proxy) {
2225        if (proxy == null) proxy = new ProxyProperties("", 0, "");
2226        log("sending Proxy Broadcast for " + proxy);
2227        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2228        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2229            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2230        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2231        mContext.sendStickyBroadcast(intent);
2232    }
2233
2234    private static class SettingsObserver extends ContentObserver {
2235        private int mWhat;
2236        private Handler mHandler;
2237        SettingsObserver(Handler handler, int what) {
2238            super(handler);
2239            mHandler = handler;
2240            mWhat = what;
2241        }
2242
2243        void observe(Context context) {
2244            ContentResolver resolver = context.getContentResolver();
2245            resolver.registerContentObserver(Settings.Secure.getUriFor(
2246                    Settings.Secure.HTTP_PROXY), false, this);
2247        }
2248
2249        @Override
2250        public void onChange(boolean selfChange) {
2251            mHandler.obtainMessage(mWhat).sendToTarget();
2252        }
2253    }
2254
2255    private void handleTetherIfaceChange(int type) {
2256        String iface = mNetTrackers[type].getLinkProperties().getInterfaceName();
2257
2258        if (isTetheringSupported()) {
2259            mTethering.handleTetherIfaceChange(iface);
2260        }
2261    }
2262
2263    private void log(String s) {
2264        Slog.d(TAG, s);
2265    }
2266
2267    private void loge(String s) {
2268        Slog.e(TAG, s);
2269    }
2270    int convertFeatureToNetworkType(String feature){
2271        int networkType = -1;
2272        if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
2273            networkType = ConnectivityManager.TYPE_MOBILE_MMS;
2274        } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
2275            networkType = ConnectivityManager.TYPE_MOBILE_SUPL;
2276        } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
2277                TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
2278            networkType = ConnectivityManager.TYPE_MOBILE_DUN;
2279        } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
2280            networkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
2281        } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
2282            networkType = ConnectivityManager.TYPE_MOBILE_FOTA;
2283        } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
2284            networkType = ConnectivityManager.TYPE_MOBILE_IMS;
2285        } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
2286            networkType = ConnectivityManager.TYPE_MOBILE_CBS;
2287        }
2288        return networkType;
2289    }
2290}
2291