OSDN Git Service

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