OSDN Git Service

am 8f678878: am 6e15b52e: am 7728e1d6: replace obsolete links. bug: 9380063
[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 static android.Manifest.permission.MANAGE_NETWORK_POLICY;
20 import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
21 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
23 import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
24 import static android.net.ConnectivityManager.TYPE_DUMMY;
25 import static android.net.ConnectivityManager.TYPE_ETHERNET;
26 import static android.net.ConnectivityManager.TYPE_MOBILE;
27 import static android.net.ConnectivityManager.TYPE_WIFI;
28 import static android.net.ConnectivityManager.TYPE_WIMAX;
29 import static android.net.ConnectivityManager.getNetworkTypeName;
30 import static android.net.ConnectivityManager.isNetworkTypeValid;
31 import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
32 import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
33
34 import android.bluetooth.BluetoothTetheringDataTracker;
35 import android.content.BroadcastReceiver;
36 import android.content.ContentResolver;
37 import android.content.Context;
38 import android.content.ContextWrapper;
39 import android.content.Intent;
40 import android.content.IntentFilter;
41 import android.content.pm.PackageManager;
42 import android.content.res.Resources;
43 import android.database.ContentObserver;
44 import android.net.CaptivePortalTracker;
45 import android.net.ConnectivityManager;
46 import android.net.DummyDataStateTracker;
47 import android.net.EthernetDataTracker;
48 import android.net.IConnectivityManager;
49 import android.net.INetworkManagementEventObserver;
50 import android.net.INetworkPolicyListener;
51 import android.net.INetworkPolicyManager;
52 import android.net.INetworkStatsService;
53 import android.net.LinkAddress;
54 import android.net.LinkProperties;
55 import android.net.LinkProperties.CompareResult;
56 import android.net.MobileDataStateTracker;
57 import android.net.NetworkConfig;
58 import android.net.NetworkInfo;
59 import android.net.NetworkInfo.DetailedState;
60 import android.net.NetworkQuotaInfo;
61 import android.net.NetworkState;
62 import android.net.NetworkStateTracker;
63 import android.net.NetworkUtils;
64 import android.net.Proxy;
65 import android.net.ProxyProperties;
66 import android.net.RouteInfo;
67 import android.net.wifi.WifiStateTracker;
68 import android.net.wimax.WimaxManagerConstants;
69 import android.os.Binder;
70 import android.os.FileUtils;
71 import android.os.Handler;
72 import android.os.HandlerThread;
73 import android.os.IBinder;
74 import android.os.INetworkManagementService;
75 import android.os.Looper;
76 import android.os.Message;
77 import android.os.Messenger;
78 import android.os.ParcelFileDescriptor;
79 import android.os.PowerManager;
80 import android.os.Process;
81 import android.os.RemoteException;
82 import android.os.ServiceManager;
83 import android.os.SystemClock;
84 import android.os.SystemProperties;
85 import android.os.UserHandle;
86 import android.provider.Settings;
87 import android.security.Credentials;
88 import android.security.KeyStore;
89 import android.text.TextUtils;
90 import android.util.Slog;
91 import android.util.SparseIntArray;
92
93 import com.android.internal.net.LegacyVpnInfo;
94 import com.android.internal.net.VpnConfig;
95 import com.android.internal.net.VpnProfile;
96 import com.android.internal.telephony.Phone;
97 import com.android.internal.telephony.PhoneConstants;
98 import com.android.internal.util.IndentingPrintWriter;
99 import com.android.server.am.BatteryStatsService;
100 import com.android.server.connectivity.Nat464Xlat;
101 import com.android.server.connectivity.Tethering;
102 import com.android.server.connectivity.Vpn;
103 import com.android.server.net.BaseNetworkObserver;
104 import com.android.server.net.LockdownVpnTracker;
105 import com.google.android.collect.Lists;
106 import com.google.android.collect.Sets;
107
108 import dalvik.system.DexClassLoader;
109
110 import java.io.FileDescriptor;
111 import java.io.IOException;
112 import java.io.PrintWriter;
113 import java.lang.reflect.Constructor;
114 import java.net.Inet4Address;
115 import java.net.Inet6Address;
116 import java.net.InetAddress;
117 import java.net.UnknownHostException;
118 import java.util.ArrayList;
119 import java.util.Arrays;
120 import java.util.Collection;
121 import java.util.GregorianCalendar;
122 import java.util.HashSet;
123 import java.util.List;
124
125 /**
126  * @hide
127  */
128 public class ConnectivityService extends IConnectivityManager.Stub {
129     private static final String TAG = "ConnectivityService";
130
131     private static final boolean DBG = true;
132     private static final boolean VDBG = false;
133
134     private static final boolean LOGD_RULES = false;
135
136     // TODO: create better separation between radio types and network types
137
138     // how long to wait before switching back to a radio's default network
139     private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
140     // system property that can override the above value
141     private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
142             "android.telephony.apn-restore";
143
144     // used in recursive route setting to add gateways for the host for which
145     // a host route was requested.
146     private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
147
148     private Tethering mTethering;
149     private boolean mTetheringConfigValid = false;
150
151     private KeyStore mKeyStore;
152
153     private Vpn mVpn;
154     private VpnCallback mVpnCallback = new VpnCallback();
155
156     private boolean mLockdownEnabled;
157     private LockdownVpnTracker mLockdownTracker;
158
159     private Nat464Xlat mClat;
160
161     /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
162     private Object mRulesLock = new Object();
163     /** Currently active network rules by UID. */
164     private SparseIntArray mUidRules = new SparseIntArray();
165     /** Set of ifaces that are costly. */
166     private HashSet<String> mMeteredIfaces = Sets.newHashSet();
167
168     /**
169      * Sometimes we want to refer to the individual network state
170      * trackers separately, and sometimes we just want to treat them
171      * abstractly.
172      */
173     private NetworkStateTracker mNetTrackers[];
174
175     /* Handles captive portal check on a network */
176     private CaptivePortalTracker mCaptivePortalTracker;
177
178     /**
179      * The link properties that define the current links
180      */
181     private LinkProperties mCurrentLinkProperties[];
182
183     /**
184      * A per Net list of the PID's that requested access to the net
185      * used both as a refcount and for per-PID DNS selection
186      */
187     private List<Integer> mNetRequestersPids[];
188
189     // priority order of the nettrackers
190     // (excluding dynamically set mNetworkPreference)
191     // TODO - move mNetworkTypePreference into this
192     private int[] mPriorityList;
193
194     private Context mContext;
195     private int mNetworkPreference;
196     private int mActiveDefaultNetwork = -1;
197     // 0 is full bad, 100 is full good
198     private int mDefaultInetCondition = 0;
199     private int mDefaultInetConditionPublished = 0;
200     private boolean mInetConditionChangeInFlight = false;
201     private int mDefaultConnectionSequence = 0;
202
203     private Object mDnsLock = new Object();
204     private int mNumDnsEntries;
205     private boolean mDnsOverridden = false;
206
207     private boolean mTestMode;
208     private static ConnectivityService sServiceInstance;
209
210     private INetworkManagementService mNetd;
211     private INetworkPolicyManager mPolicyManager;
212
213     private static final int ENABLED  = 1;
214     private static final int DISABLED = 0;
215
216     private static final boolean ADD = true;
217     private static final boolean REMOVE = false;
218
219     private static final boolean TO_DEFAULT_TABLE = true;
220     private static final boolean TO_SECONDARY_TABLE = false;
221
222     /**
223      * used internally as a delayed event to make us switch back to the
224      * default network
225      */
226     private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
227
228     /**
229      * used internally to change our mobile data enabled flag
230      */
231     private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
232
233     /**
234      * used internally to change our network preference setting
235      * arg1 = networkType to prefer
236      */
237     private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
238
239     /**
240      * used internally to synchronize inet condition reports
241      * arg1 = networkType
242      * arg2 = condition (0 bad, 100 good)
243      */
244     private static final int EVENT_INET_CONDITION_CHANGE = 4;
245
246     /**
247      * used internally to mark the end of inet condition hold periods
248      * arg1 = networkType
249      */
250     private static final int EVENT_INET_CONDITION_HOLD_END = 5;
251
252     /**
253      * used internally to set enable/disable cellular data
254      * arg1 = ENBALED or DISABLED
255      */
256     private static final int EVENT_SET_MOBILE_DATA = 7;
257
258     /**
259      * used internally to clear a wakelock when transitioning
260      * from one net to another
261      */
262     private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
263
264     /**
265      * used internally to reload global proxy settings
266      */
267     private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
268
269     /**
270      * used internally to set external dependency met/unmet
271      * arg1 = ENABLED (met) or DISABLED (unmet)
272      * arg2 = NetworkType
273      */
274     private static final int EVENT_SET_DEPENDENCY_MET = 10;
275
276     /**
277      * used internally to restore DNS properties back to the
278      * default network
279      */
280     private static final int EVENT_RESTORE_DNS = 11;
281
282     /**
283      * used internally to send a sticky broadcast delayed.
284      */
285     private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 12;
286
287     /**
288      * Used internally to
289      * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
290      */
291     private static final int EVENT_SET_POLICY_DATA_ENABLE = 13;
292
293     private static final int EVENT_VPN_STATE_CHANGED = 14;
294
295     /** Handler used for internal events. */
296     private InternalHandler mHandler;
297     /** Handler used for incoming {@link NetworkStateTracker} events. */
298     private NetworkStateTrackerHandler mTrackerHandler;
299
300     // list of DeathRecipients used to make sure features are turned off when
301     // a process dies
302     private List<FeatureUser> mFeatureUsers;
303
304     private boolean mSystemReady;
305     private Intent mInitialBroadcast;
306
307     private PowerManager.WakeLock mNetTransitionWakeLock;
308     private String mNetTransitionWakeLockCausedBy = "";
309     private int mNetTransitionWakeLockSerialNumber;
310     private int mNetTransitionWakeLockTimeout;
311
312     private InetAddress mDefaultDns;
313
314     // this collection is used to refcount the added routes - if there are none left
315     // it's time to remove the route from the route table
316     private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
317
318     // used in DBG mode to track inet condition reports
319     private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
320     private ArrayList mInetLog;
321
322     // track the current default http proxy - tell the world if we get a new one (real change)
323     private ProxyProperties mDefaultProxy = null;
324     private Object mProxyLock = new Object();
325     private boolean mDefaultProxyDisabled = false;
326
327     // track the global proxy.
328     private ProxyProperties mGlobalProxy = null;
329
330     private SettingsObserver mSettingsObserver;
331
332     NetworkConfig[] mNetConfigs;
333     int mNetworksDefined;
334
335     private static class RadioAttributes {
336         public int mSimultaneity;
337         public int mType;
338         public RadioAttributes(String init) {
339             String fragments[] = init.split(",");
340             mType = Integer.parseInt(fragments[0]);
341             mSimultaneity = Integer.parseInt(fragments[1]);
342         }
343     }
344     RadioAttributes[] mRadioAttributes;
345
346     // the set of network types that can only be enabled by system/sig apps
347     List mProtectedNetworks;
348
349     public ConnectivityService(Context context, INetworkManagementService netd,
350             INetworkStatsService statsService, INetworkPolicyManager policyManager) {
351         // Currently, omitting a NetworkFactory will create one internally
352         // TODO: create here when we have cleaner WiMAX support
353         this(context, netd, statsService, policyManager, null);
354     }
355
356     public ConnectivityService(Context context, INetworkManagementService netManager,
357             INetworkStatsService statsService, INetworkPolicyManager policyManager,
358             NetworkFactory netFactory) {
359         if (DBG) log("ConnectivityService starting up");
360
361         HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
362         handlerThread.start();
363         mHandler = new InternalHandler(handlerThread.getLooper());
364         mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
365
366         if (netFactory == null) {
367             netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
368         }
369
370         // setup our unique device name
371         if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
372             String id = Settings.Secure.getString(context.getContentResolver(),
373                     Settings.Secure.ANDROID_ID);
374             if (id != null && id.length() > 0) {
375                 String name = new String("android-").concat(id);
376                 SystemProperties.set("net.hostname", name);
377             }
378         }
379
380         // read our default dns server ip
381         String dns = Settings.Global.getString(context.getContentResolver(),
382                 Settings.Global.DEFAULT_DNS_SERVER);
383         if (dns == null || dns.length() == 0) {
384             dns = context.getResources().getString(
385                     com.android.internal.R.string.config_default_dns_server);
386         }
387         try {
388             mDefaultDns = NetworkUtils.numericToInetAddress(dns);
389         } catch (IllegalArgumentException e) {
390             loge("Error setting defaultDns using " + dns);
391         }
392
393         mContext = checkNotNull(context, "missing Context");
394         mNetd = checkNotNull(netManager, "missing INetworkManagementService");
395         mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
396         mKeyStore = KeyStore.getInstance();
397
398         try {
399             mPolicyManager.registerListener(mPolicyListener);
400         } catch (RemoteException e) {
401             // ouch, no rules updates means some processes may never get network
402             loge("unable to register INetworkPolicyListener" + e.toString());
403         }
404
405         final PowerManager powerManager = (PowerManager) context.getSystemService(
406                 Context.POWER_SERVICE);
407         mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
408         mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
409                 com.android.internal.R.integer.config_networkTransitionTimeout);
410
411         mNetTrackers = new NetworkStateTracker[
412                 ConnectivityManager.MAX_NETWORK_TYPE+1];
413         mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
414
415         mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
416         mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
417
418         // Load device network attributes from resources
419         String[] raStrings = context.getResources().getStringArray(
420                 com.android.internal.R.array.radioAttributes);
421         for (String raString : raStrings) {
422             RadioAttributes r = new RadioAttributes(raString);
423             if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
424                 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
425                 continue;
426             }
427             if (mRadioAttributes[r.mType] != null) {
428                 loge("Error in radioAttributes - ignoring attempt to redefine type " +
429                         r.mType);
430                 continue;
431             }
432             mRadioAttributes[r.mType] = r;
433         }
434
435         // TODO: What is the "correct" way to do determine if this is a wifi only device?
436         boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
437         log("wifiOnly=" + wifiOnly);
438         String[] naStrings = context.getResources().getStringArray(
439                 com.android.internal.R.array.networkAttributes);
440         for (String naString : naStrings) {
441             try {
442                 NetworkConfig n = new NetworkConfig(naString);
443                 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
444                     loge("Error in networkAttributes - ignoring attempt to define type " +
445                             n.type);
446                     continue;
447                 }
448                 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
449                     log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
450                             n.type);
451                     continue;
452                 }
453                 if (mNetConfigs[n.type] != null) {
454                     loge("Error in networkAttributes - ignoring attempt to redefine type " +
455                             n.type);
456                     continue;
457                 }
458                 if (mRadioAttributes[n.radio] == null) {
459                     loge("Error in networkAttributes - ignoring attempt to use undefined " +
460                             "radio " + n.radio + " in network type " + n.type);
461                     continue;
462                 }
463                 mNetConfigs[n.type] = n;
464                 mNetworksDefined++;
465             } catch(Exception e) {
466                 // ignore it - leave the entry null
467             }
468         }
469
470         mProtectedNetworks = new ArrayList<Integer>();
471         int[] protectedNetworks = context.getResources().getIntArray(
472                 com.android.internal.R.array.config_protectedNetworks);
473         for (int p : protectedNetworks) {
474             if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
475                 mProtectedNetworks.add(p);
476             } else {
477                 if (DBG) loge("Ignoring protectedNetwork " + p);
478             }
479         }
480
481         // high priority first
482         mPriorityList = new int[mNetworksDefined];
483         {
484             int insertionPoint = mNetworksDefined-1;
485             int currentLowest = 0;
486             int nextLowest = 0;
487             while (insertionPoint > -1) {
488                 for (NetworkConfig na : mNetConfigs) {
489                     if (na == null) continue;
490                     if (na.priority < currentLowest) continue;
491                     if (na.priority > currentLowest) {
492                         if (na.priority < nextLowest || nextLowest == 0) {
493                             nextLowest = na.priority;
494                         }
495                         continue;
496                     }
497                     mPriorityList[insertionPoint--] = na.type;
498                 }
499                 currentLowest = nextLowest;
500                 nextLowest = 0;
501             }
502         }
503
504         // Update mNetworkPreference according to user mannually first then overlay config.xml
505         mNetworkPreference = getPersistedNetworkPreference();
506         if (mNetworkPreference == -1) {
507             for (int n : mPriorityList) {
508                 if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
509                     mNetworkPreference = n;
510                     break;
511                 }
512             }
513             if (mNetworkPreference == -1) {
514                 throw new IllegalStateException(
515                         "You should set at least one default Network in config.xml!");
516             }
517         }
518
519         mNetRequestersPids =
520                 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
521         for (int i : mPriorityList) {
522             mNetRequestersPids[i] = new ArrayList<Integer>();
523         }
524
525         mFeatureUsers = new ArrayList<FeatureUser>();
526
527         mTestMode = SystemProperties.get("cm.test.mode").equals("true")
528                 && SystemProperties.get("ro.build.type").equals("eng");
529
530         // Create and start trackers for hard-coded networks
531         for (int targetNetworkType : mPriorityList) {
532             final NetworkConfig config = mNetConfigs[targetNetworkType];
533             final NetworkStateTracker tracker;
534             try {
535                 tracker = netFactory.createTracker(targetNetworkType, config);
536                 mNetTrackers[targetNetworkType] = tracker;
537             } catch (IllegalArgumentException e) {
538                 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
539                         + " tracker: " + e);
540                 continue;
541             }
542
543             tracker.startMonitoring(context, mTrackerHandler);
544             if (config.isDefault()) {
545                 tracker.reconnect();
546             }
547         }
548
549         mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
550         mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 ||
551                                   mTethering.getTetherableWifiRegexs().length != 0 ||
552                                   mTethering.getTetherableBluetoothRegexs().length != 0) &&
553                                  mTethering.getUpstreamIfaceTypes().length != 0);
554
555         mVpn = new Vpn(mContext, mVpnCallback, mNetd, this);
556         mVpn.startMonitoring(mContext, mTrackerHandler);
557
558         mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
559
560         try {
561             mNetd.registerObserver(mTethering);
562             mNetd.registerObserver(mDataActivityObserver);
563             mNetd.registerObserver(mClat);
564         } catch (RemoteException e) {
565             loge("Error registering observer :" + e);
566         }
567
568         if (DBG) {
569             mInetLog = new ArrayList();
570         }
571
572         mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
573         mSettingsObserver.observe(mContext);
574
575         mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
576         loadGlobalProxy();
577     }
578
579     /**
580      * Factory that creates {@link NetworkStateTracker} instances using given
581      * {@link NetworkConfig}.
582      */
583     public interface NetworkFactory {
584         public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
585     }
586
587     private static class DefaultNetworkFactory implements NetworkFactory {
588         private final Context mContext;
589         private final Handler mTrackerHandler;
590
591         public DefaultNetworkFactory(Context context, Handler trackerHandler) {
592             mContext = context;
593             mTrackerHandler = trackerHandler;
594         }
595
596         @Override
597         public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
598             switch (config.radio) {
599                 case TYPE_WIFI:
600                     return new WifiStateTracker(targetNetworkType, config.name);
601                 case TYPE_MOBILE:
602                     return new MobileDataStateTracker(targetNetworkType, config.name);
603                 case TYPE_DUMMY:
604                     return new DummyDataStateTracker(targetNetworkType, config.name);
605                 case TYPE_BLUETOOTH:
606                     return BluetoothTetheringDataTracker.getInstance();
607                 case TYPE_WIMAX:
608                     return makeWimaxStateTracker(mContext, mTrackerHandler);
609                 case TYPE_ETHERNET:
610                     return EthernetDataTracker.getInstance();
611                 default:
612                     throw new IllegalArgumentException(
613                             "Trying to create a NetworkStateTracker for an unknown radio type: "
614                             + config.radio);
615             }
616         }
617     }
618
619     /**
620      * Loads external WiMAX library and registers as system service, returning a
621      * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
622      * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
623      */
624     private static NetworkStateTracker makeWimaxStateTracker(
625             Context context, Handler trackerHandler) {
626         // Initialize Wimax
627         DexClassLoader wimaxClassLoader;
628         Class wimaxStateTrackerClass = null;
629         Class wimaxServiceClass = null;
630         Class wimaxManagerClass;
631         String wimaxJarLocation;
632         String wimaxLibLocation;
633         String wimaxManagerClassName;
634         String wimaxServiceClassName;
635         String wimaxStateTrackerClassName;
636
637         NetworkStateTracker wimaxStateTracker = null;
638
639         boolean isWimaxEnabled = context.getResources().getBoolean(
640                 com.android.internal.R.bool.config_wimaxEnabled);
641
642         if (isWimaxEnabled) {
643             try {
644                 wimaxJarLocation = context.getResources().getString(
645                         com.android.internal.R.string.config_wimaxServiceJarLocation);
646                 wimaxLibLocation = context.getResources().getString(
647                         com.android.internal.R.string.config_wimaxNativeLibLocation);
648                 wimaxManagerClassName = context.getResources().getString(
649                         com.android.internal.R.string.config_wimaxManagerClassname);
650                 wimaxServiceClassName = context.getResources().getString(
651                         com.android.internal.R.string.config_wimaxServiceClassname);
652                 wimaxStateTrackerClassName = context.getResources().getString(
653                         com.android.internal.R.string.config_wimaxStateTrackerClassname);
654
655                 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation);
656                 wimaxClassLoader =  new DexClassLoader(wimaxJarLocation,
657                         new ContextWrapper(context).getCacheDir().getAbsolutePath(),
658                         wimaxLibLocation, ClassLoader.getSystemClassLoader());
659
660                 try {
661                     wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
662                     wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
663                     wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
664                 } catch (ClassNotFoundException ex) {
665                     loge("Exception finding Wimax classes: " + ex.toString());
666                     return null;
667                 }
668             } catch(Resources.NotFoundException ex) {
669                 loge("Wimax Resources does not exist!!! ");
670                 return null;
671             }
672
673             try {
674                 if (DBG) log("Starting Wimax Service... ");
675
676                 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
677                         (new Class[] {Context.class, Handler.class});
678                 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
679                         context, trackerHandler);
680
681                 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
682                         (new Class[] {Context.class, wimaxStateTrackerClass});
683                 wmxSrvConst.setAccessible(true);
684                 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
685                 wmxSrvConst.setAccessible(false);
686
687                 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
688
689             } catch(Exception ex) {
690                 loge("Exception creating Wimax classes: " + ex.toString());
691                 return null;
692             }
693         } else {
694             loge("Wimax is not enabled or not added to the network attributes!!! ");
695             return null;
696         }
697
698         return wimaxStateTracker;
699     }
700
701     /**
702      * Sets the preferred network.
703      * @param preference the new preference
704      */
705     public void setNetworkPreference(int preference) {
706         enforceChangePermission();
707
708         mHandler.sendMessage(
709                 mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
710     }
711
712     public int getNetworkPreference() {
713         enforceAccessPermission();
714         int preference;
715         synchronized(this) {
716             preference = mNetworkPreference;
717         }
718         return preference;
719     }
720
721     private void handleSetNetworkPreference(int preference) {
722         if (ConnectivityManager.isNetworkTypeValid(preference) &&
723                 mNetConfigs[preference] != null &&
724                 mNetConfigs[preference].isDefault()) {
725             if (mNetworkPreference != preference) {
726                 final ContentResolver cr = mContext.getContentResolver();
727                 Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
728                 synchronized(this) {
729                     mNetworkPreference = preference;
730                 }
731                 enforcePreference();
732             }
733         }
734     }
735
736     private int getConnectivityChangeDelay() {
737         final ContentResolver cr = mContext.getContentResolver();
738
739         /** Check system properties for the default value then use secure settings value, if any. */
740         int defaultDelay = SystemProperties.getInt(
741                 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
742                 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
743         return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
744                 defaultDelay);
745     }
746
747     private int getPersistedNetworkPreference() {
748         final ContentResolver cr = mContext.getContentResolver();
749
750         final int networkPrefSetting = Settings.Global
751                 .getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
752
753         return networkPrefSetting;
754     }
755
756     /**
757      * Make the state of network connectivity conform to the preference settings
758      * In this method, we only tear down a non-preferred network. Establishing
759      * a connection to the preferred network is taken care of when we handle
760      * the disconnect event from the non-preferred network
761      * (see {@link #handleDisconnect(NetworkInfo)}).
762      */
763     private void enforcePreference() {
764         if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
765             return;
766
767         if (!mNetTrackers[mNetworkPreference].isAvailable())
768             return;
769
770         for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
771             if (t != mNetworkPreference && mNetTrackers[t] != null &&
772                     mNetTrackers[t].getNetworkInfo().isConnected()) {
773                 if (DBG) {
774                     log("tearing down " + mNetTrackers[t].getNetworkInfo() +
775                             " in enforcePreference");
776                 }
777                 teardown(mNetTrackers[t]);
778             }
779         }
780     }
781
782     private boolean teardown(NetworkStateTracker netTracker) {
783         if (netTracker.teardown()) {
784             netTracker.setTeardownRequested(true);
785             return true;
786         } else {
787             return false;
788         }
789     }
790
791     /**
792      * Check if UID should be blocked from using the network represented by the
793      * given {@link NetworkStateTracker}.
794      */
795     private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
796         final String iface = tracker.getLinkProperties().getInterfaceName();
797
798         final boolean networkCostly;
799         final int uidRules;
800         synchronized (mRulesLock) {
801             networkCostly = mMeteredIfaces.contains(iface);
802             uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
803         }
804
805         if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
806             return true;
807         }
808
809         // no restrictive rules; network is visible
810         return false;
811     }
812
813     /**
814      * Return a filtered {@link NetworkInfo}, potentially marked
815      * {@link DetailedState#BLOCKED} based on
816      * {@link #isNetworkBlocked(NetworkStateTracker, int)}.
817      */
818     private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
819         NetworkInfo info = tracker.getNetworkInfo();
820         if (isNetworkBlocked(tracker, uid)) {
821             // network is blocked; clone and override state
822             info = new NetworkInfo(info);
823             info.setDetailedState(DetailedState.BLOCKED, null, null);
824         }
825         if (mLockdownTracker != null) {
826             info = mLockdownTracker.augmentNetworkInfo(info);
827         }
828         return info;
829     }
830
831     /**
832      * Return NetworkInfo for the active (i.e., connected) network interface.
833      * It is assumed that at most one network is active at a time. If more
834      * than one is active, it is indeterminate which will be returned.
835      * @return the info for the active network, or {@code null} if none is
836      * active
837      */
838     @Override
839     public NetworkInfo getActiveNetworkInfo() {
840         enforceAccessPermission();
841         final int uid = Binder.getCallingUid();
842         return getNetworkInfo(mActiveDefaultNetwork, uid);
843     }
844
845     public NetworkInfo getActiveNetworkInfoUnfiltered() {
846         enforceAccessPermission();
847         if (isNetworkTypeValid(mActiveDefaultNetwork)) {
848             final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
849             if (tracker != null) {
850                 return tracker.getNetworkInfo();
851             }
852         }
853         return null;
854     }
855
856     @Override
857     public NetworkInfo getActiveNetworkInfoForUid(int uid) {
858         enforceConnectivityInternalPermission();
859         return getNetworkInfo(mActiveDefaultNetwork, uid);
860     }
861
862     @Override
863     public NetworkInfo getNetworkInfo(int networkType) {
864         enforceAccessPermission();
865         final int uid = Binder.getCallingUid();
866         return getNetworkInfo(networkType, uid);
867     }
868
869     private NetworkInfo getNetworkInfo(int networkType, int uid) {
870         NetworkInfo info = null;
871         if (isNetworkTypeValid(networkType)) {
872             final NetworkStateTracker tracker = mNetTrackers[networkType];
873             if (tracker != null) {
874                 info = getFilteredNetworkInfo(tracker, uid);
875             }
876         }
877         return info;
878     }
879
880     @Override
881     public NetworkInfo[] getAllNetworkInfo() {
882         enforceAccessPermission();
883         final int uid = Binder.getCallingUid();
884         final ArrayList<NetworkInfo> result = Lists.newArrayList();
885         synchronized (mRulesLock) {
886             for (NetworkStateTracker tracker : mNetTrackers) {
887                 if (tracker != null) {
888                     result.add(getFilteredNetworkInfo(tracker, uid));
889                 }
890             }
891         }
892         return result.toArray(new NetworkInfo[result.size()]);
893     }
894
895     @Override
896     public boolean isNetworkSupported(int networkType) {
897         enforceAccessPermission();
898         return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
899     }
900
901     /**
902      * Return LinkProperties for the active (i.e., connected) default
903      * network interface.  It is assumed that at most one default network
904      * is active at a time. If more than one is active, it is indeterminate
905      * which will be returned.
906      * @return the ip properties for the active network, or {@code null} if
907      * none is active
908      */
909     @Override
910     public LinkProperties getActiveLinkProperties() {
911         return getLinkProperties(mActiveDefaultNetwork);
912     }
913
914     @Override
915     public LinkProperties getLinkProperties(int networkType) {
916         enforceAccessPermission();
917         if (isNetworkTypeValid(networkType)) {
918             final NetworkStateTracker tracker = mNetTrackers[networkType];
919             if (tracker != null) {
920                 return tracker.getLinkProperties();
921             }
922         }
923         return null;
924     }
925
926     @Override
927     public NetworkState[] getAllNetworkState() {
928         enforceAccessPermission();
929         final int uid = Binder.getCallingUid();
930         final ArrayList<NetworkState> result = Lists.newArrayList();
931         synchronized (mRulesLock) {
932             for (NetworkStateTracker tracker : mNetTrackers) {
933                 if (tracker != null) {
934                     final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
935                     result.add(new NetworkState(
936                             info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
937                 }
938             }
939         }
940         return result.toArray(new NetworkState[result.size()]);
941     }
942
943     private NetworkState getNetworkStateUnchecked(int networkType) {
944         if (isNetworkTypeValid(networkType)) {
945             final NetworkStateTracker tracker = mNetTrackers[networkType];
946             if (tracker != null) {
947                 return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
948                         tracker.getLinkCapabilities());
949             }
950         }
951         return null;
952     }
953
954     @Override
955     public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
956         enforceAccessPermission();
957
958         final long token = Binder.clearCallingIdentity();
959         try {
960             final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
961             if (state != null) {
962                 try {
963                     return mPolicyManager.getNetworkQuotaInfo(state);
964                 } catch (RemoteException e) {
965                 }
966             }
967             return null;
968         } finally {
969             Binder.restoreCallingIdentity(token);
970         }
971     }
972
973     @Override
974     public boolean isActiveNetworkMetered() {
975         enforceAccessPermission();
976         final long token = Binder.clearCallingIdentity();
977         try {
978             return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
979         } finally {
980             Binder.restoreCallingIdentity(token);
981         }
982     }
983
984     private boolean isNetworkMeteredUnchecked(int networkType) {
985         final NetworkState state = getNetworkStateUnchecked(networkType);
986         if (state != null) {
987             try {
988                 return mPolicyManager.isNetworkMetered(state);
989             } catch (RemoteException e) {
990             }
991         }
992         return false;
993     }
994
995     public boolean setRadios(boolean turnOn) {
996         boolean result = true;
997         enforceChangePermission();
998         for (NetworkStateTracker t : mNetTrackers) {
999             if (t != null) result = t.setRadio(turnOn) && result;
1000         }
1001         return result;
1002     }
1003
1004     public boolean setRadio(int netType, boolean turnOn) {
1005         enforceChangePermission();
1006         if (!ConnectivityManager.isNetworkTypeValid(netType)) {
1007             return false;
1008         }
1009         NetworkStateTracker tracker = mNetTrackers[netType];
1010         return tracker != null && tracker.setRadio(turnOn);
1011     }
1012
1013     private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1014         @Override
1015         public void interfaceClassDataActivityChanged(String label, boolean active) {
1016             int deviceType = Integer.parseInt(label);
1017             sendDataActivityBroadcast(deviceType, active);
1018         }
1019     };
1020
1021     /**
1022      * Used to notice when the calling process dies so we can self-expire
1023      *
1024      * Also used to know if the process has cleaned up after itself when
1025      * our auto-expire timer goes off.  The timer has a link to an object.
1026      *
1027      */
1028     private class FeatureUser implements IBinder.DeathRecipient {
1029         int mNetworkType;
1030         String mFeature;
1031         IBinder mBinder;
1032         int mPid;
1033         int mUid;
1034         long mCreateTime;
1035
1036         FeatureUser(int type, String feature, IBinder binder) {
1037             super();
1038             mNetworkType = type;
1039             mFeature = feature;
1040             mBinder = binder;
1041             mPid = getCallingPid();
1042             mUid = getCallingUid();
1043             mCreateTime = System.currentTimeMillis();
1044
1045             try {
1046                 mBinder.linkToDeath(this, 0);
1047             } catch (RemoteException e) {
1048                 binderDied();
1049             }
1050         }
1051
1052         void unlinkDeathRecipient() {
1053             mBinder.unlinkToDeath(this, 0);
1054         }
1055
1056         public void binderDied() {
1057             log("ConnectivityService FeatureUser binderDied(" +
1058                     mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
1059                     (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1060             stopUsingNetworkFeature(this, false);
1061         }
1062
1063         public void expire() {
1064             if (VDBG) {
1065                 log("ConnectivityService FeatureUser expire(" +
1066                         mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
1067                         (System.currentTimeMillis() - mCreateTime) + " mSec ago");
1068             }
1069             stopUsingNetworkFeature(this, false);
1070         }
1071
1072         public boolean isSameUser(FeatureUser u) {
1073             if (u == null) return false;
1074
1075             return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
1076         }
1077
1078         public boolean isSameUser(int pid, int uid, int networkType, String feature) {
1079             if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
1080                 TextUtils.equals(mFeature, feature)) {
1081                 return true;
1082             }
1083             return false;
1084         }
1085
1086         public String toString() {
1087             return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
1088                     (System.currentTimeMillis() - mCreateTime) + " mSec ago";
1089         }
1090     }
1091
1092     // javadoc from interface
1093     public int startUsingNetworkFeature(int networkType, String feature,
1094             IBinder binder) {
1095         long startTime = 0;
1096         if (DBG) {
1097             startTime = SystemClock.elapsedRealtime();
1098         }
1099         if (VDBG) {
1100             log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
1101                     + Binder.getCallingUid());
1102         }
1103         enforceChangePermission();
1104         try {
1105             if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
1106                     mNetConfigs[networkType] == null) {
1107                 return PhoneConstants.APN_REQUEST_FAILED;
1108             }
1109
1110             FeatureUser f = new FeatureUser(networkType, feature, binder);
1111
1112             // TODO - move this into individual networktrackers
1113             int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1114
1115             if (mLockdownEnabled) {
1116                 // Since carrier APNs usually aren't available from VPN
1117                 // endpoint, mark them as unavailable.
1118                 return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1119             }
1120
1121             if (mProtectedNetworks.contains(usedNetworkType)) {
1122                 enforceConnectivityInternalPermission();
1123             }
1124
1125             // if UID is restricted, don't allow them to bring up metered APNs
1126             final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
1127             final int uidRules;
1128             synchronized (mRulesLock) {
1129                 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
1130             }
1131             if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
1132                 return PhoneConstants.APN_REQUEST_FAILED;
1133             }
1134
1135             NetworkStateTracker network = mNetTrackers[usedNetworkType];
1136             if (network != null) {
1137                 Integer currentPid = new Integer(getCallingPid());
1138                 if (usedNetworkType != networkType) {
1139                     NetworkInfo ni = network.getNetworkInfo();
1140
1141                     if (ni.isAvailable() == false) {
1142                         if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
1143                             if (DBG) log("special network not available ni=" + ni.getTypeName());
1144                             return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1145                         } else {
1146                             // else make the attempt anyway - probably giving REQUEST_STARTED below
1147                             if (DBG) {
1148                                 log("special network not available, but try anyway ni=" +
1149                                         ni.getTypeName());
1150                             }
1151                         }
1152                     }
1153
1154                     int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
1155
1156                     synchronized(this) {
1157                         boolean addToList = true;
1158                         if (restoreTimer < 0) {
1159                             // In case there is no timer is specified for the feature,
1160                             // make sure we don't add duplicate entry with the same request.
1161                             for (FeatureUser u : mFeatureUsers) {
1162                                 if (u.isSameUser(f)) {
1163                                     // Duplicate user is found. Do not add.
1164                                     addToList = false;
1165                                     break;
1166                                 }
1167                             }
1168                         }
1169
1170                         if (addToList) mFeatureUsers.add(f);
1171                         if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1172                             // this gets used for per-pid dns when connected
1173                             mNetRequestersPids[usedNetworkType].add(currentPid);
1174                         }
1175                     }
1176
1177                     if (restoreTimer >= 0) {
1178                         mHandler.sendMessageDelayed(mHandler.obtainMessage(
1179                                 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
1180                     }
1181
1182                     if ((ni.isConnectedOrConnecting() == true) &&
1183                             !network.isTeardownRequested()) {
1184                         if (ni.isConnected() == true) {
1185                             final long token = Binder.clearCallingIdentity();
1186                             try {
1187                                 // add the pid-specific dns
1188                                 handleDnsConfigurationChange(usedNetworkType);
1189                                 if (VDBG) log("special network already active");
1190                             } finally {
1191                                 Binder.restoreCallingIdentity(token);
1192                             }
1193                             return PhoneConstants.APN_ALREADY_ACTIVE;
1194                         }
1195                         if (VDBG) log("special network already connecting");
1196                         return PhoneConstants.APN_REQUEST_STARTED;
1197                     }
1198
1199                     // check if the radio in play can make another contact
1200                     // assume if cannot for now
1201
1202                     if (DBG) {
1203                         log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
1204                                 feature);
1205                     }
1206                     if (network.reconnect()) {
1207                         return PhoneConstants.APN_REQUEST_STARTED;
1208                     } else {
1209                         return PhoneConstants.APN_REQUEST_FAILED;
1210                     }
1211                 } else {
1212                     // need to remember this unsupported request so we respond appropriately on stop
1213                     synchronized(this) {
1214                         mFeatureUsers.add(f);
1215                         if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
1216                             // this gets used for per-pid dns when connected
1217                             mNetRequestersPids[usedNetworkType].add(currentPid);
1218                         }
1219                     }
1220                     return -1;
1221                 }
1222             }
1223             return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
1224          } finally {
1225             if (DBG) {
1226                 final long execTime = SystemClock.elapsedRealtime() - startTime;
1227                 if (execTime > 250) {
1228                     loge("startUsingNetworkFeature took too long: " + execTime + "ms");
1229                 } else {
1230                     if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
1231                 }
1232             }
1233          }
1234     }
1235
1236     // javadoc from interface
1237     public int stopUsingNetworkFeature(int networkType, String feature) {
1238         enforceChangePermission();
1239
1240         int pid = getCallingPid();
1241         int uid = getCallingUid();
1242
1243         FeatureUser u = null;
1244         boolean found = false;
1245
1246         synchronized(this) {
1247             for (FeatureUser x : mFeatureUsers) {
1248                 if (x.isSameUser(pid, uid, networkType, feature)) {
1249                     u = x;
1250                     found = true;
1251                     break;
1252                 }
1253             }
1254         }
1255         if (found && u != null) {
1256             // stop regardless of how many other time this proc had called start
1257             return stopUsingNetworkFeature(u, true);
1258         } else {
1259             // none found!
1260             if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
1261             return 1;
1262         }
1263     }
1264
1265     private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
1266         int networkType = u.mNetworkType;
1267         String feature = u.mFeature;
1268         int pid = u.mPid;
1269         int uid = u.mUid;
1270
1271         NetworkStateTracker tracker = null;
1272         boolean callTeardown = false;  // used to carry our decision outside of sync block
1273
1274         if (VDBG) {
1275             log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
1276         }
1277
1278         if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1279             if (DBG) {
1280                 log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1281                         ", net is invalid");
1282             }
1283             return -1;
1284         }
1285
1286         // need to link the mFeatureUsers list with the mNetRequestersPids state in this
1287         // sync block
1288         synchronized(this) {
1289             // check if this process still has an outstanding start request
1290             if (!mFeatureUsers.contains(u)) {
1291                 if (VDBG) {
1292                     log("stopUsingNetworkFeature: this process has no outstanding requests" +
1293                         ", ignoring");
1294                 }
1295                 return 1;
1296             }
1297             u.unlinkDeathRecipient();
1298             mFeatureUsers.remove(mFeatureUsers.indexOf(u));
1299             // If we care about duplicate requests, check for that here.
1300             //
1301             // This is done to support the extension of a request - the app
1302             // can request we start the network feature again and renew the
1303             // auto-shutoff delay.  Normal "stop" calls from the app though
1304             // do not pay attention to duplicate requests - in effect the
1305             // API does not refcount and a single stop will counter multiple starts.
1306             if (ignoreDups == false) {
1307                 for (FeatureUser x : mFeatureUsers) {
1308                     if (x.isSameUser(u)) {
1309                         if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
1310                         return 1;
1311                     }
1312                 }
1313             }
1314
1315             // TODO - move to individual network trackers
1316             int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
1317
1318             tracker =  mNetTrackers[usedNetworkType];
1319             if (tracker == null) {
1320                 if (DBG) {
1321                     log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1322                             " no known tracker for used net type " + usedNetworkType);
1323                 }
1324                 return -1;
1325             }
1326             if (usedNetworkType != networkType) {
1327                 Integer currentPid = new Integer(pid);
1328                 mNetRequestersPids[usedNetworkType].remove(currentPid);
1329
1330                 final long token = Binder.clearCallingIdentity();
1331                 try {
1332                     reassessPidDns(pid, true);
1333                 } finally {
1334                     Binder.restoreCallingIdentity(token);
1335                 }
1336                 flushVmDnsCache();
1337                 if (mNetRequestersPids[usedNetworkType].size() != 0) {
1338                     if (VDBG) {
1339                         log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1340                                 " others still using it");
1341                     }
1342                     return 1;
1343                 }
1344                 callTeardown = true;
1345             } else {
1346                 if (DBG) {
1347                     log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
1348                             " not a known feature - dropping");
1349                 }
1350             }
1351         }
1352
1353         if (callTeardown) {
1354             if (DBG) {
1355                 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
1356             }
1357             tracker.teardown();
1358             return 1;
1359         } else {
1360             return -1;
1361         }
1362     }
1363
1364     /**
1365      * @deprecated use requestRouteToHostAddress instead
1366      *
1367      * Ensure that a network route exists to deliver traffic to the specified
1368      * host via the specified network interface.
1369      * @param networkType the type of the network over which traffic to the
1370      * specified host is to be routed
1371      * @param hostAddress the IP address of the host to which the route is
1372      * desired
1373      * @return {@code true} on success, {@code false} on failure
1374      */
1375     public boolean requestRouteToHost(int networkType, int hostAddress) {
1376         InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
1377
1378         if (inetAddress == null) {
1379             return false;
1380         }
1381
1382         return requestRouteToHostAddress(networkType, inetAddress.getAddress());
1383     }
1384
1385     /**
1386      * Ensure that a network route exists to deliver traffic to the specified
1387      * host via the specified network interface.
1388      * @param networkType the type of the network over which traffic to the
1389      * specified host is to be routed
1390      * @param hostAddress the IP address of the host to which the route is
1391      * desired
1392      * @return {@code true} on success, {@code false} on failure
1393      */
1394     public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
1395         enforceChangePermission();
1396         if (mProtectedNetworks.contains(networkType)) {
1397             enforceConnectivityInternalPermission();
1398         }
1399
1400         if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1401             if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1402             return false;
1403         }
1404         NetworkStateTracker tracker = mNetTrackers[networkType];
1405         DetailedState netState = tracker.getNetworkInfo().getDetailedState();
1406
1407         if (tracker == null || (netState != DetailedState.CONNECTED &&
1408                 netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
1409                 tracker.isTeardownRequested()) {
1410             if (VDBG) {
1411                 log("requestRouteToHostAddress on down network " +
1412                            "(" + networkType + ") - dropped");
1413             }
1414             return false;
1415         }
1416         final long token = Binder.clearCallingIdentity();
1417         try {
1418             InetAddress addr = InetAddress.getByAddress(hostAddress);
1419             LinkProperties lp = tracker.getLinkProperties();
1420             return addRouteToAddress(lp, addr);
1421         } catch (UnknownHostException e) {
1422             if (DBG) log("requestRouteToHostAddress got " + e.toString());
1423         } finally {
1424             Binder.restoreCallingIdentity(token);
1425         }
1426         return false;
1427     }
1428
1429     private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1430         return modifyRoute(p, r, 0, ADD, toDefaultTable);
1431     }
1432
1433     private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
1434         return modifyRoute(p, r, 0, REMOVE, toDefaultTable);
1435     }
1436
1437     private boolean addRouteToAddress(LinkProperties lp, InetAddress addr) {
1438         return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE);
1439     }
1440
1441     private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
1442         return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE);
1443     }
1444
1445     private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
1446             boolean toDefaultTable) {
1447         RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1448         if (bestRoute == null) {
1449             bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1450         } else {
1451             String iface = bestRoute.getInterface();
1452             if (bestRoute.getGateway().equals(addr)) {
1453                 // if there is no better route, add the implied hostroute for our gateway
1454                 bestRoute = RouteInfo.makeHostRoute(addr, iface);
1455             } else {
1456                 // if we will connect to this through another route, add a direct route
1457                 // to it's gateway
1458                 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1459             }
1460         }
1461         return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable);
1462     }
1463
1464     private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
1465             boolean toDefaultTable) {
1466         if ((lp == null) || (r == null)) {
1467             if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
1468             return false;
1469         }
1470
1471         if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
1472             loge("Error modifying route - too much recursion");
1473             return false;
1474         }
1475
1476         String ifaceName = r.getInterface();
1477         if(ifaceName == null) {
1478             loge("Error modifying route - no interface name");
1479             return false;
1480         }
1481         if (r.hasGateway()) {
1482             RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
1483             if (bestRoute != null) {
1484                 if (bestRoute.getGateway().equals(r.getGateway())) {
1485                     // if there is no better route, add the implied hostroute for our gateway
1486                     bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
1487                 } else {
1488                     // if we will connect to our gateway through another route, add a direct
1489                     // route to it's gateway
1490                     bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
1491                                                         bestRoute.getGateway(),
1492                                                         ifaceName);
1493                 }
1494                 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable);
1495             }
1496         }
1497         if (doAdd) {
1498             if (VDBG) log("Adding " + r + " for interface " + ifaceName);
1499             try {
1500                 if (toDefaultTable) {
1501                     mAddedRoutes.add(r);  // only track default table - only one apps can effect
1502                     mNetd.addRoute(ifaceName, r);
1503                 } else {
1504                     mNetd.addSecondaryRoute(ifaceName, r);
1505                 }
1506             } catch (Exception e) {
1507                 // never crash - catch them all
1508                 if (DBG) loge("Exception trying to add a route: " + e);
1509                 return false;
1510             }
1511         } else {
1512             // if we remove this one and there are no more like it, then refcount==0 and
1513             // we can remove it from the table
1514             if (toDefaultTable) {
1515                 mAddedRoutes.remove(r);
1516                 if (mAddedRoutes.contains(r) == false) {
1517                     if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1518                     try {
1519                         mNetd.removeRoute(ifaceName, r);
1520                     } catch (Exception e) {
1521                         // never crash - catch them all
1522                         if (VDBG) loge("Exception trying to remove a route: " + e);
1523                         return false;
1524                     }
1525                 } else {
1526                     if (VDBG) log("not removing " + r + " as it's still in use");
1527                 }
1528             } else {
1529                 if (VDBG) log("Removing " + r + " for interface " + ifaceName);
1530                 try {
1531                     mNetd.removeSecondaryRoute(ifaceName, r);
1532                 } catch (Exception e) {
1533                     // never crash - catch them all
1534                     if (VDBG) loge("Exception trying to remove a route: " + e);
1535                     return false;
1536                 }
1537             }
1538         }
1539         return true;
1540     }
1541
1542     /**
1543      * @see ConnectivityManager#getMobileDataEnabled()
1544      */
1545     public boolean getMobileDataEnabled() {
1546         // TODO: This detail should probably be in DataConnectionTracker's
1547         //       which is where we store the value and maybe make this
1548         //       asynchronous.
1549         enforceAccessPermission();
1550         boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
1551                 Settings.Global.MOBILE_DATA, 1) == 1;
1552         if (VDBG) log("getMobileDataEnabled returning " + retVal);
1553         return retVal;
1554     }
1555
1556     public void setDataDependency(int networkType, boolean met) {
1557         enforceConnectivityInternalPermission();
1558
1559         mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
1560                 (met ? ENABLED : DISABLED), networkType));
1561     }
1562
1563     private void handleSetDependencyMet(int networkType, boolean met) {
1564         if (mNetTrackers[networkType] != null) {
1565             if (DBG) {
1566                 log("handleSetDependencyMet(" + networkType + ", " + met + ")");
1567             }
1568             mNetTrackers[networkType].setDependencyMet(met);
1569         }
1570     }
1571
1572     private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1573         @Override
1574         public void onUidRulesChanged(int uid, int uidRules) {
1575             // caller is NPMS, since we only register with them
1576             if (LOGD_RULES) {
1577                 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1578             }
1579
1580             synchronized (mRulesLock) {
1581                 // skip update when we've already applied rules
1582                 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1583                 if (oldRules == uidRules) return;
1584
1585                 mUidRules.put(uid, uidRules);
1586             }
1587
1588             // TODO: notify UID when it has requested targeted updates
1589         }
1590
1591         @Override
1592         public void onMeteredIfacesChanged(String[] meteredIfaces) {
1593             // caller is NPMS, since we only register with them
1594             if (LOGD_RULES) {
1595                 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1596             }
1597
1598             synchronized (mRulesLock) {
1599                 mMeteredIfaces.clear();
1600                 for (String iface : meteredIfaces) {
1601                     mMeteredIfaces.add(iface);
1602                 }
1603             }
1604         }
1605
1606         @Override
1607         public void onRestrictBackgroundChanged(boolean restrictBackground) {
1608             // caller is NPMS, since we only register with them
1609             if (LOGD_RULES) {
1610                 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1611             }
1612
1613             // kick off connectivity change broadcast for active network, since
1614             // global background policy change is radical.
1615             final int networkType = mActiveDefaultNetwork;
1616             if (isNetworkTypeValid(networkType)) {
1617                 final NetworkStateTracker tracker = mNetTrackers[networkType];
1618                 if (tracker != null) {
1619                     final NetworkInfo info = tracker.getNetworkInfo();
1620                     if (info != null && info.isConnected()) {
1621                         sendConnectedBroadcast(info);
1622                     }
1623                 }
1624             }
1625         }
1626     };
1627
1628     /**
1629      * @see ConnectivityManager#setMobileDataEnabled(boolean)
1630      */
1631     public void setMobileDataEnabled(boolean enabled) {
1632         enforceChangePermission();
1633         if (DBG) log("setMobileDataEnabled(" + enabled + ")");
1634
1635         mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
1636                 (enabled ? ENABLED : DISABLED), 0));
1637     }
1638
1639     private void handleSetMobileData(boolean enabled) {
1640         if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
1641             if (VDBG) {
1642                 log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
1643             }
1644             mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
1645         }
1646         if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
1647             if (VDBG) {
1648                 log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
1649             }
1650             mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
1651         }
1652     }
1653
1654     @Override
1655     public void setPolicyDataEnable(int networkType, boolean enabled) {
1656         // only someone like NPMS should only be calling us
1657         mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1658
1659         mHandler.sendMessage(mHandler.obtainMessage(
1660                 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
1661     }
1662
1663     private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
1664         if (isNetworkTypeValid(networkType)) {
1665             final NetworkStateTracker tracker = mNetTrackers[networkType];
1666             if (tracker != null) {
1667                 tracker.setPolicyDataEnable(enabled);
1668             }
1669         }
1670     }
1671
1672     private void enforceAccessPermission() {
1673         mContext.enforceCallingOrSelfPermission(
1674                 android.Manifest.permission.ACCESS_NETWORK_STATE,
1675                 "ConnectivityService");
1676     }
1677
1678     private void enforceChangePermission() {
1679         mContext.enforceCallingOrSelfPermission(
1680                 android.Manifest.permission.CHANGE_NETWORK_STATE,
1681                 "ConnectivityService");
1682     }
1683
1684     // TODO Make this a special check when it goes public
1685     private void enforceTetherChangePermission() {
1686         mContext.enforceCallingOrSelfPermission(
1687                 android.Manifest.permission.CHANGE_NETWORK_STATE,
1688                 "ConnectivityService");
1689     }
1690
1691     private void enforceTetherAccessPermission() {
1692         mContext.enforceCallingOrSelfPermission(
1693                 android.Manifest.permission.ACCESS_NETWORK_STATE,
1694                 "ConnectivityService");
1695     }
1696
1697     private void enforceConnectivityInternalPermission() {
1698         mContext.enforceCallingOrSelfPermission(
1699                 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1700                 "ConnectivityService");
1701     }
1702
1703     /**
1704      * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
1705      * network, we ignore it. If it is for the active network, we send out a
1706      * broadcast. But first, we check whether it might be possible to connect
1707      * to a different network.
1708      * @param info the {@code NetworkInfo} for the network
1709      */
1710     private void handleDisconnect(NetworkInfo info) {
1711
1712         int prevNetType = info.getType();
1713
1714         mNetTrackers[prevNetType].setTeardownRequested(false);
1715
1716         // Remove idletimer previously setup in {@code handleConnect}
1717         removeDataActivityTracking(prevNetType);
1718
1719         /*
1720          * If the disconnected network is not the active one, then don't report
1721          * this as a loss of connectivity. What probably happened is that we're
1722          * getting the disconnect for a network that we explicitly disabled
1723          * in accordance with network preference policies.
1724          */
1725         if (!mNetConfigs[prevNetType].isDefault()) {
1726             List<Integer> pids = mNetRequestersPids[prevNetType];
1727             for (Integer pid : pids) {
1728                 // will remove them because the net's no longer connected
1729                 // need to do this now as only now do we know the pids and
1730                 // can properly null things that are no longer referenced.
1731                 reassessPidDns(pid.intValue(), false);
1732             }
1733         }
1734
1735         Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1736         intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1737         intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1738         if (info.isFailover()) {
1739             intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1740             info.setFailover(false);
1741         }
1742         if (info.getReason() != null) {
1743             intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1744         }
1745         if (info.getExtraInfo() != null) {
1746             intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1747                     info.getExtraInfo());
1748         }
1749
1750         if (mNetConfigs[prevNetType].isDefault()) {
1751             tryFailover(prevNetType);
1752             if (mActiveDefaultNetwork != -1) {
1753                 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1754                 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1755             } else {
1756                 mDefaultInetConditionPublished = 0; // we're not connected anymore
1757                 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1758             }
1759         }
1760         intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1761
1762         // Reset interface if no other connections are using the same interface
1763         boolean doReset = true;
1764         LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
1765         if (linkProperties != null) {
1766             String oldIface = linkProperties.getInterfaceName();
1767             if (TextUtils.isEmpty(oldIface) == false) {
1768                 for (NetworkStateTracker networkStateTracker : mNetTrackers) {
1769                     if (networkStateTracker == null) continue;
1770                     NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
1771                     if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
1772                         LinkProperties l = networkStateTracker.getLinkProperties();
1773                         if (l == null) continue;
1774                         if (oldIface.equals(l.getInterfaceName())) {
1775                             doReset = false;
1776                             break;
1777                         }
1778                     }
1779                 }
1780             }
1781         }
1782
1783         // do this before we broadcast the change
1784         handleConnectivityChange(prevNetType, doReset);
1785
1786         final Intent immediateIntent = new Intent(intent);
1787         immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1788         sendStickyBroadcast(immediateIntent);
1789         sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
1790         /*
1791          * If the failover network is already connected, then immediately send
1792          * out a followup broadcast indicating successful failover
1793          */
1794         if (mActiveDefaultNetwork != -1) {
1795             sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
1796                     getConnectivityChangeDelay());
1797         }
1798     }
1799
1800     private void tryFailover(int prevNetType) {
1801         /*
1802          * If this is a default network, check if other defaults are available.
1803          * Try to reconnect on all available and let them hash it out when
1804          * more than one connects.
1805          */
1806         if (mNetConfigs[prevNetType].isDefault()) {
1807             if (mActiveDefaultNetwork == prevNetType) {
1808                 mActiveDefaultNetwork = -1;
1809             }
1810
1811             // don't signal a reconnect for anything lower or equal priority than our
1812             // current connected default
1813             // TODO - don't filter by priority now - nice optimization but risky
1814 //            int currentPriority = -1;
1815 //            if (mActiveDefaultNetwork != -1) {
1816 //                currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
1817 //            }
1818             for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
1819                 if (checkType == prevNetType) continue;
1820                 if (mNetConfigs[checkType] == null) continue;
1821                 if (!mNetConfigs[checkType].isDefault()) continue;
1822                 if (mNetTrackers[checkType] == null) continue;
1823
1824 // Enabling the isAvailable() optimization caused mobile to not get
1825 // selected if it was in the middle of error handling. Specifically
1826 // a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
1827 // would not be available and we wouldn't get connected to anything.
1828 // So removing the isAvailable() optimization below for now. TODO: This
1829 // optimization should work and we need to investigate why it doesn't work.
1830 // This could be related to how DEACTIVATE_DATA_CALL is reporting its
1831 // complete before it is really complete.
1832 //                if (!mNetTrackers[checkType].isAvailable()) continue;
1833
1834 //                if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
1835
1836                 NetworkStateTracker checkTracker = mNetTrackers[checkType];
1837                 NetworkInfo checkInfo = checkTracker.getNetworkInfo();
1838                 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
1839                     checkInfo.setFailover(true);
1840                     checkTracker.reconnect();
1841                 }
1842                 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
1843             }
1844         }
1845     }
1846
1847     public void sendConnectedBroadcast(NetworkInfo info) {
1848         enforceConnectivityInternalPermission();
1849         sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1850         sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
1851     }
1852
1853     private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
1854         sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1855         sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
1856     }
1857
1858     private void sendInetConditionBroadcast(NetworkInfo info) {
1859         sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1860     }
1861
1862     private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
1863         if (mLockdownTracker != null) {
1864             info = mLockdownTracker.augmentNetworkInfo(info);
1865         }
1866
1867         Intent intent = new Intent(bcastType);
1868         intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1869         intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1870         if (info.isFailover()) {
1871             intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1872             info.setFailover(false);
1873         }
1874         if (info.getReason() != null) {
1875             intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1876         }
1877         if (info.getExtraInfo() != null) {
1878             intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1879                     info.getExtraInfo());
1880         }
1881         intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1882         return intent;
1883     }
1884
1885     private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1886         sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1887     }
1888
1889     private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
1890         sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
1891     }
1892
1893     private void sendDataActivityBroadcast(int deviceType, boolean active) {
1894         Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1895         intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1896         intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
1897         final long ident = Binder.clearCallingIdentity();
1898         try {
1899             mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1900                     RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1901         } finally {
1902             Binder.restoreCallingIdentity(ident);
1903         }
1904     }
1905
1906     /**
1907      * Called when an attempt to fail over to another network has failed.
1908      * @param info the {@link NetworkInfo} for the failed network
1909      */
1910     private void handleConnectionFailure(NetworkInfo info) {
1911         mNetTrackers[info.getType()].setTeardownRequested(false);
1912
1913         String reason = info.getReason();
1914         String extraInfo = info.getExtraInfo();
1915
1916         String reasonText;
1917         if (reason == null) {
1918             reasonText = ".";
1919         } else {
1920             reasonText = " (" + reason + ").";
1921         }
1922         loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
1923
1924         Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
1925         intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1926         intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1927         if (getActiveNetworkInfo() == null) {
1928             intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1929         }
1930         if (reason != null) {
1931             intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
1932         }
1933         if (extraInfo != null) {
1934             intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
1935         }
1936         if (info.isFailover()) {
1937             intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1938             info.setFailover(false);
1939         }
1940
1941         if (mNetConfigs[info.getType()].isDefault()) {
1942             tryFailover(info.getType());
1943             if (mActiveDefaultNetwork != -1) {
1944                 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
1945                 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
1946             } else {
1947                 mDefaultInetConditionPublished = 0;
1948                 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
1949             }
1950         }
1951
1952         intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1953
1954         final Intent immediateIntent = new Intent(intent);
1955         immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
1956         sendStickyBroadcast(immediateIntent);
1957         sendStickyBroadcast(intent);
1958         /*
1959          * If the failover network is already connected, then immediately send
1960          * out a followup broadcast indicating successful failover
1961          */
1962         if (mActiveDefaultNetwork != -1) {
1963             sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
1964         }
1965     }
1966
1967     private void sendStickyBroadcast(Intent intent) {
1968         synchronized(this) {
1969             if (!mSystemReady) {
1970                 mInitialBroadcast = new Intent(intent);
1971             }
1972             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1973             if (VDBG) {
1974                 log("sendStickyBroadcast: action=" + intent.getAction());
1975             }
1976
1977             final long ident = Binder.clearCallingIdentity();
1978             try {
1979                 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1980             } finally {
1981                 Binder.restoreCallingIdentity(ident);
1982             }
1983         }
1984     }
1985
1986     private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
1987         if (delayMs <= 0) {
1988             sendStickyBroadcast(intent);
1989         } else {
1990             if (VDBG) {
1991                 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
1992                         + intent.getAction());
1993             }
1994             mHandler.sendMessageDelayed(mHandler.obtainMessage(
1995                     EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
1996         }
1997     }
1998
1999     void systemReady() {
2000         synchronized(this) {
2001             mSystemReady = true;
2002             if (mInitialBroadcast != null) {
2003                 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
2004                 mInitialBroadcast = null;
2005             }
2006         }
2007         // load the global proxy at startup
2008         mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
2009
2010         // Try bringing up tracker, but if KeyStore isn't ready yet, wait
2011         // for user to unlock device.
2012         if (!updateLockdownVpn()) {
2013             final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
2014             mContext.registerReceiver(mUserPresentReceiver, filter);
2015         }
2016     }
2017
2018     private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
2019         @Override
2020         public void onReceive(Context context, Intent intent) {
2021             // Try creating lockdown tracker, since user present usually means
2022             // unlocked keystore.
2023             if (updateLockdownVpn()) {
2024                 mContext.unregisterReceiver(this);
2025             }
2026         }
2027     };
2028
2029     private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
2030         if ((type != mNetworkPreference &&
2031                     mNetConfigs[mActiveDefaultNetwork].priority >
2032                     mNetConfigs[type].priority) ||
2033                 mNetworkPreference == mActiveDefaultNetwork) return false;
2034         return true;
2035     }
2036
2037     private void handleConnect(NetworkInfo info) {
2038         final int newNetType = info.getType();
2039
2040         setupDataActivityTracking(newNetType);
2041
2042         // snapshot isFailover, because sendConnectedBroadcast() resets it
2043         boolean isFailover = info.isFailover();
2044         final NetworkStateTracker thisNet = mNetTrackers[newNetType];
2045         final String thisIface = thisNet.getLinkProperties().getInterfaceName();
2046
2047         // if this is a default net and other default is running
2048         // kill the one not preferred
2049         if (mNetConfigs[newNetType].isDefault()) {
2050             if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
2051                 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
2052                     // tear down the other
2053                     NetworkStateTracker otherNet =
2054                             mNetTrackers[mActiveDefaultNetwork];
2055                     if (DBG) {
2056                         log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
2057                             " teardown");
2058                     }
2059                     if (!teardown(otherNet)) {
2060                         loge("Network declined teardown request");
2061                         teardown(thisNet);
2062                         return;
2063                     }
2064                 } else {
2065                        // don't accept this one
2066                         if (VDBG) {
2067                             log("Not broadcasting CONNECT_ACTION " +
2068                                 "to torn down network " + info.getTypeName());
2069                         }
2070                         teardown(thisNet);
2071                         return;
2072                 }
2073             }
2074             synchronized (ConnectivityService.this) {
2075                 // have a new default network, release the transition wakelock in a second
2076                 // if it's held.  The second pause is to allow apps to reconnect over the
2077                 // new network
2078                 if (mNetTransitionWakeLock.isHeld()) {
2079                     mHandler.sendMessageDelayed(mHandler.obtainMessage(
2080                             EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2081                             mNetTransitionWakeLockSerialNumber, 0),
2082                             1000);
2083                 }
2084             }
2085             mActiveDefaultNetwork = newNetType;
2086             // this will cause us to come up initially as unconnected and switching
2087             // to connected after our normal pause unless somebody reports us as reall
2088             // disconnected
2089             mDefaultInetConditionPublished = 0;
2090             mDefaultConnectionSequence++;
2091             mInetConditionChangeInFlight = false;
2092             // Don't do this - if we never sign in stay, grey
2093             //reportNetworkCondition(mActiveDefaultNetwork, 100);
2094         }
2095         thisNet.setTeardownRequested(false);
2096         updateNetworkSettings(thisNet);
2097         handleConnectivityChange(newNetType, false);
2098         sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
2099
2100         // notify battery stats service about this network
2101         if (thisIface != null) {
2102             try {
2103                 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
2104             } catch (RemoteException e) {
2105                 // ignored; service lives in system_server
2106             }
2107         }
2108     }
2109
2110     private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
2111         if (DBG) log("Captive portal check " + info);
2112         int type = info.getType();
2113         final NetworkStateTracker thisNet = mNetTrackers[type];
2114         if (mNetConfigs[type].isDefault()) {
2115             if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
2116                 if (isNewNetTypePreferredOverCurrentNetType(type)) {
2117                     if (DBG) log("Captive check on " + info.getTypeName());
2118                     mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
2119                     return;
2120                 } else {
2121                     if (DBG) log("Tear down low priority net " + info.getTypeName());
2122                     teardown(thisNet);
2123                     return;
2124                 }
2125             }
2126         }
2127
2128         thisNet.captivePortalCheckComplete();
2129     }
2130
2131     /** @hide */
2132     public void captivePortalCheckComplete(NetworkInfo info) {
2133         enforceConnectivityInternalPermission();
2134         mNetTrackers[info.getType()].captivePortalCheckComplete();
2135     }
2136
2137     /**
2138      * Setup data activity tracking for the given network interface.
2139      *
2140      * Every {@code setupDataActivityTracking} should be paired with a
2141      * {@link removeDataActivityTracking} for cleanup.
2142      */
2143     private void setupDataActivityTracking(int type) {
2144         final NetworkStateTracker thisNet = mNetTrackers[type];
2145         final String iface = thisNet.getLinkProperties().getInterfaceName();
2146
2147         final int timeout;
2148
2149         if (ConnectivityManager.isNetworkTypeMobile(type)) {
2150             timeout = Settings.Global.getInt(mContext.getContentResolver(),
2151                                              Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
2152                                              0);
2153             // Canonicalize mobile network type
2154             type = ConnectivityManager.TYPE_MOBILE;
2155         } else if (ConnectivityManager.TYPE_WIFI == type) {
2156             timeout = Settings.Global.getInt(mContext.getContentResolver(),
2157                                              Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
2158                                              0);
2159         } else {
2160             // do not track any other networks
2161             timeout = 0;
2162         }
2163
2164         if (timeout > 0 && iface != null) {
2165             try {
2166                 mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
2167             } catch (RemoteException e) {
2168             }
2169         }
2170     }
2171
2172     /**
2173      * Remove data activity tracking when network disconnects.
2174      */
2175     private void removeDataActivityTracking(int type) {
2176         final NetworkStateTracker net = mNetTrackers[type];
2177         final String iface = net.getLinkProperties().getInterfaceName();
2178
2179         if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
2180                               ConnectivityManager.TYPE_WIFI == type)) {
2181             try {
2182                 // the call fails silently if no idletimer setup for this interface
2183                 mNetd.removeIdleTimer(iface);
2184             } catch (RemoteException e) {
2185             }
2186         }
2187     }
2188
2189     /**
2190      * After a change in the connectivity state of a network. We're mainly
2191      * concerned with making sure that the list of DNS servers is set up
2192      * according to which networks are connected, and ensuring that the
2193      * right routing table entries exist.
2194      */
2195     private void handleConnectivityChange(int netType, boolean doReset) {
2196         int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
2197
2198         /*
2199          * If a non-default network is enabled, add the host routes that
2200          * will allow it's DNS servers to be accessed.
2201          */
2202         handleDnsConfigurationChange(netType);
2203
2204         LinkProperties curLp = mCurrentLinkProperties[netType];
2205         LinkProperties newLp = null;
2206
2207         if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2208             newLp = mNetTrackers[netType].getLinkProperties();
2209             if (VDBG) {
2210                 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2211                         " doReset=" + doReset + " resetMask=" + resetMask +
2212                         "\n   curLp=" + curLp +
2213                         "\n   newLp=" + newLp);
2214             }
2215
2216             if (curLp != null) {
2217                 if (curLp.isIdenticalInterfaceName(newLp)) {
2218                     CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
2219                     if ((car.removed.size() != 0) || (car.added.size() != 0)) {
2220                         for (LinkAddress linkAddr : car.removed) {
2221                             if (linkAddr.getAddress() instanceof Inet4Address) {
2222                                 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
2223                             }
2224                             if (linkAddr.getAddress() instanceof Inet6Address) {
2225                                 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
2226                             }
2227                         }
2228                         if (DBG) {
2229                             log("handleConnectivityChange: addresses changed" +
2230                                     " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
2231                                     "\n   car=" + car);
2232                         }
2233                     } else {
2234                         if (DBG) {
2235                             log("handleConnectivityChange: address are the same reset per doReset" +
2236                                    " linkProperty[" + netType + "]:" +
2237                                    " resetMask=" + resetMask);
2238                         }
2239                     }
2240                 } else {
2241                     resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
2242                     if (DBG) {
2243                         log("handleConnectivityChange: interface not not equivalent reset both" +
2244                                 " linkProperty[" + netType + "]:" +
2245                                 " resetMask=" + resetMask);
2246                     }
2247                 }
2248             }
2249             if (mNetConfigs[netType].isDefault()) {
2250                 handleApplyDefaultProxy(newLp.getHttpProxy());
2251             }
2252         } else {
2253             if (VDBG) {
2254                 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
2255                         " doReset=" + doReset + " resetMask=" + resetMask +
2256                         "\n  curLp=" + curLp +
2257                         "\n  newLp= null");
2258             }
2259         }
2260         mCurrentLinkProperties[netType] = newLp;
2261         boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault());
2262
2263         if (resetMask != 0 || resetDns) {
2264             if (curLp != null) {
2265                 for (String iface : curLp.getAllInterfaceNames()) {
2266                     if (TextUtils.isEmpty(iface) == false) {
2267                         if (resetMask != 0) {
2268                             if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
2269                             NetworkUtils.resetConnections(iface, resetMask);
2270
2271                             // Tell VPN the interface is down. It is a temporary
2272                             // but effective fix to make VPN aware of the change.
2273                             if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
2274                                 mVpn.interfaceStatusChanged(iface, false);
2275                             }
2276                         }
2277                         if (resetDns) {
2278                             flushVmDnsCache();
2279                             if (VDBG) log("resetting DNS cache for " + iface);
2280                             try {
2281                                 mNetd.flushInterfaceDnsCache(iface);
2282                             } catch (Exception e) {
2283                                 // never crash - catch them all
2284                                 if (DBG) loge("Exception resetting dns cache: " + e);
2285                             }
2286                         }
2287                     } else {
2288                         loge("Can't reset connection for type "+netType);
2289                     }
2290                 }
2291             }
2292         }
2293
2294         // Update 464xlat state.
2295         NetworkStateTracker tracker = mNetTrackers[netType];
2296         if (mClat.requiresClat(netType, tracker)) {
2297             // If the connection was previously using clat, but is not using it now, stop the clat
2298             // daemon. Normally, this happens automatically when the connection disconnects, but if
2299             // the disconnect is not reported, or if the connection's LinkProperties changed for
2300             // some other reason (e.g., handoff changes the IP addresses on the link), it would
2301             // still be running. If it's not running, then stopping it is a no-op.
2302             if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
2303                 mClat.stopClat();
2304             }
2305             // If the link requires clat to be running, then start the daemon now.
2306             if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
2307                 mClat.startClat(tracker);
2308             } else {
2309                 mClat.stopClat();
2310             }
2311         }
2312
2313         // TODO: Temporary notifying upstread change to Tethering.
2314         //       @see bug/4455071
2315         /** Notify TetheringService if interface name has been changed. */
2316         if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
2317                              PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
2318             if (isTetheringSupported()) {
2319                 mTethering.handleTetherIfaceChange();
2320             }
2321         }
2322     }
2323
2324     /**
2325      * Add and remove routes using the old properties (null if not previously connected),
2326      * new properties (null if becoming disconnected).  May even be double null, which
2327      * is a noop.
2328      * Uses isLinkDefault to determine if default routes should be set or conversely if
2329      * host routes should be set to the dns servers
2330      * returns a boolean indicating the routes changed
2331      */
2332     private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
2333             boolean isLinkDefault) {
2334         Collection<RouteInfo> routesToAdd = null;
2335         CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
2336         CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
2337         if (curLp != null) {
2338             // check for the delta between the current set and the new
2339             routeDiff = curLp.compareRoutes(newLp);
2340             dnsDiff = curLp.compareDnses(newLp);
2341         } else if (newLp != null) {
2342             routeDiff.added = newLp.getAllRoutes();
2343             dnsDiff.added = newLp.getDnses();
2344         }
2345
2346         boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
2347
2348         for (RouteInfo r : routeDiff.removed) {
2349             if (isLinkDefault || ! r.isDefaultRoute()) {
2350                 removeRoute(curLp, r, TO_DEFAULT_TABLE);
2351             }
2352             if (isLinkDefault == false) {
2353                 // remove from a secondary route table
2354                 removeRoute(curLp, r, TO_SECONDARY_TABLE);
2355             }
2356         }
2357
2358         if (!isLinkDefault) {
2359             // handle DNS routes
2360             if (routesChanged) {
2361                 // routes changed - remove all old dns entries and add new
2362                 if (curLp != null) {
2363                     for (InetAddress oldDns : curLp.getDnses()) {
2364                         removeRouteToAddress(curLp, oldDns);
2365                     }
2366                 }
2367                 if (newLp != null) {
2368                     for (InetAddress newDns : newLp.getDnses()) {
2369                         addRouteToAddress(newLp, newDns);
2370                     }
2371                 }
2372             } else {
2373                 // no change in routes, check for change in dns themselves
2374                 for (InetAddress oldDns : dnsDiff.removed) {
2375                     removeRouteToAddress(curLp, oldDns);
2376                 }
2377                 for (InetAddress newDns : dnsDiff.added) {
2378                     addRouteToAddress(newLp, newDns);
2379                 }
2380             }
2381         }
2382
2383         for (RouteInfo r :  routeDiff.added) {
2384             if (isLinkDefault || ! r.isDefaultRoute()) {
2385                 addRoute(newLp, r, TO_DEFAULT_TABLE);
2386             } else {
2387                 // add to a secondary route table
2388                 addRoute(newLp, r, TO_SECONDARY_TABLE);
2389
2390                 // many radios add a default route even when we don't want one.
2391                 // remove the default route unless somebody else has asked for it
2392                 String ifaceName = newLp.getInterfaceName();
2393                 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
2394                     if (VDBG) log("Removing " + r + " for interface " + ifaceName);
2395                     try {
2396                         mNetd.removeRoute(ifaceName, r);
2397                     } catch (Exception e) {
2398                         // never crash - catch them all
2399                         if (DBG) loge("Exception trying to remove a route: " + e);
2400                     }
2401                 }
2402             }
2403         }
2404
2405         return routesChanged;
2406     }
2407
2408
2409    /**
2410      * Reads the network specific TCP buffer sizes from SystemProperties
2411      * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
2412      * wide use
2413      */
2414    private void updateNetworkSettings(NetworkStateTracker nt) {
2415         String key = nt.getTcpBufferSizesPropName();
2416         String bufferSizes = key == null ? null : SystemProperties.get(key);
2417
2418         if (TextUtils.isEmpty(bufferSizes)) {
2419             if (VDBG) log(key + " not found in system properties. Using defaults");
2420
2421             // Setting to default values so we won't be stuck to previous values
2422             key = "net.tcp.buffersize.default";
2423             bufferSizes = SystemProperties.get(key);
2424         }
2425
2426         // Set values in kernel
2427         if (bufferSizes.length() != 0) {
2428             if (VDBG) {
2429                 log("Setting TCP values: [" + bufferSizes
2430                         + "] which comes from [" + key + "]");
2431             }
2432             setBufferSize(bufferSizes);
2433         }
2434     }
2435
2436    /**
2437      * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
2438      * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
2439      *
2440      * @param bufferSizes in the format of "readMin, readInitial, readMax,
2441      *        writeMin, writeInitial, writeMax"
2442      */
2443     private void setBufferSize(String bufferSizes) {
2444         try {
2445             String[] values = bufferSizes.split(",");
2446
2447             if (values.length == 6) {
2448               final String prefix = "/sys/kernel/ipv4/tcp_";
2449                 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
2450                 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
2451                 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
2452                 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
2453                 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
2454                 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
2455             } else {
2456                 loge("Invalid buffersize string: " + bufferSizes);
2457             }
2458         } catch (IOException e) {
2459             loge("Can't set tcp buffer sizes:" + e);
2460         }
2461     }
2462
2463     /**
2464      * Adjust the per-process dns entries (net.dns<x>.<pid>) based
2465      * on the highest priority active net which this process requested.
2466      * If there aren't any, clear it out
2467      */
2468     private void reassessPidDns(int pid, boolean doBump)
2469     {
2470         if (VDBG) log("reassessPidDns for pid " + pid);
2471         Integer myPid = new Integer(pid);
2472         for(int i : mPriorityList) {
2473             if (mNetConfigs[i].isDefault()) {
2474                 continue;
2475             }
2476             NetworkStateTracker nt = mNetTrackers[i];
2477             if (nt.getNetworkInfo().isConnected() &&
2478                     !nt.isTeardownRequested()) {
2479                 LinkProperties p = nt.getLinkProperties();
2480                 if (p == null) continue;
2481                 if (mNetRequestersPids[i].contains(myPid)) {
2482                     try {
2483                         mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2484                     } catch (Exception e) {
2485                         Slog.e(TAG, "exception reasseses pid dns: " + e);
2486                     }
2487                     return;
2488                 }
2489            }
2490         }
2491         // nothing found - delete
2492         try {
2493             mNetd.clearDnsInterfaceForPid(pid);
2494         } catch (Exception e) {
2495             Slog.e(TAG, "exception clear interface from pid: " + e);
2496         }
2497     }
2498
2499     private void flushVmDnsCache() {
2500         /*
2501          * Tell the VMs to toss their DNS caches
2502          */
2503         Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
2504         intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
2505         /*
2506          * Connectivity events can happen before boot has completed ...
2507          */
2508         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2509         final long ident = Binder.clearCallingIdentity();
2510         try {
2511             mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2512         } finally {
2513             Binder.restoreCallingIdentity(ident);
2514         }
2515     }
2516
2517     // Caller must grab mDnsLock.
2518     private void updateDnsLocked(String network, String iface,
2519             Collection<InetAddress> dnses, String domains) {
2520         int last = 0;
2521         if (dnses.size() == 0 && mDefaultDns != null) {
2522             dnses = new ArrayList();
2523             dnses.add(mDefaultDns);
2524             if (DBG) {
2525                 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
2526             }
2527         }
2528
2529         try {
2530             mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
2531             mNetd.setDefaultInterfaceForDns(iface);
2532             for (InetAddress dns : dnses) {
2533                 ++last;
2534                 String key = "net.dns" + last;
2535                 String value = dns.getHostAddress();
2536                 SystemProperties.set(key, value);
2537             }
2538             for (int i = last + 1; i <= mNumDnsEntries; ++i) {
2539                 String key = "net.dns" + i;
2540                 SystemProperties.set(key, "");
2541             }
2542             mNumDnsEntries = last;
2543         } catch (Exception e) {
2544             if (DBG) loge("exception setting default dns interface: " + e);
2545         }
2546     }
2547
2548     private void handleDnsConfigurationChange(int netType) {
2549         // add default net's dns entries
2550         NetworkStateTracker nt = mNetTrackers[netType];
2551         if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
2552             LinkProperties p = nt.getLinkProperties();
2553             if (p == null) return;
2554             Collection<InetAddress> dnses = p.getDnses();
2555             if (mNetConfigs[netType].isDefault()) {
2556                 String network = nt.getNetworkInfo().getTypeName();
2557                 synchronized (mDnsLock) {
2558                     if (!mDnsOverridden) {
2559                         updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains());
2560                     }
2561                 }
2562             } else {
2563                 try {
2564                     mNetd.setDnsServersForInterface(p.getInterfaceName(),
2565                             NetworkUtils.makeStrings(dnses), p.getDomains());
2566                 } catch (Exception e) {
2567                     if (DBG) loge("exception setting dns servers: " + e);
2568                 }
2569                 // set per-pid dns for attached secondary nets
2570                 List<Integer> pids = mNetRequestersPids[netType];
2571                 for (Integer pid : pids) {
2572                     try {
2573                         mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
2574                     } catch (Exception e) {
2575                         Slog.e(TAG, "exception setting interface for pid: " + e);
2576                     }
2577                 }
2578             }
2579             flushVmDnsCache();
2580         }
2581     }
2582
2583     private int getRestoreDefaultNetworkDelay(int networkType) {
2584         String restoreDefaultNetworkDelayStr = SystemProperties.get(
2585                 NETWORK_RESTORE_DELAY_PROP_NAME);
2586         if(restoreDefaultNetworkDelayStr != null &&
2587                 restoreDefaultNetworkDelayStr.length() != 0) {
2588             try {
2589                 return Integer.valueOf(restoreDefaultNetworkDelayStr);
2590             } catch (NumberFormatException e) {
2591             }
2592         }
2593         // if the system property isn't set, use the value for the apn type
2594         int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2595
2596         if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
2597                 (mNetConfigs[networkType] != null)) {
2598             ret = mNetConfigs[networkType].restoreTime;
2599         }
2600         return ret;
2601     }
2602
2603     @Override
2604     protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2605         final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
2606         if (mContext.checkCallingOrSelfPermission(
2607                 android.Manifest.permission.DUMP)
2608                 != PackageManager.PERMISSION_GRANTED) {
2609             pw.println("Permission Denial: can't dump ConnectivityService " +
2610                     "from from pid=" + Binder.getCallingPid() + ", uid=" +
2611                     Binder.getCallingUid());
2612             return;
2613         }
2614
2615         // TODO: add locking to get atomic snapshot
2616         pw.println();
2617         for (int i = 0; i < mNetTrackers.length; i++) {
2618             final NetworkStateTracker nst = mNetTrackers[i];
2619             if (nst != null) {
2620                 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
2621                 pw.increaseIndent();
2622                 if (nst.getNetworkInfo().isConnected()) {
2623                     pw.println("Active network: " + nst.getNetworkInfo().
2624                             getTypeName());
2625                 }
2626                 pw.println(nst.getNetworkInfo());
2627                 pw.println(nst.getLinkProperties());
2628                 pw.println(nst);
2629                 pw.println();
2630                 pw.decreaseIndent();
2631             }
2632         }
2633
2634         pw.println("Network Requester Pids:");
2635         pw.increaseIndent();
2636         for (int net : mPriorityList) {
2637             String pidString = net + ": ";
2638             for (Integer pid : mNetRequestersPids[net]) {
2639                 pidString = pidString + pid.toString() + ", ";
2640             }
2641             pw.println(pidString);
2642         }
2643         pw.println();
2644         pw.decreaseIndent();
2645
2646         pw.println("FeatureUsers:");
2647         pw.increaseIndent();
2648         for (Object requester : mFeatureUsers) {
2649             pw.println(requester.toString());
2650         }
2651         pw.println();
2652         pw.decreaseIndent();
2653
2654         synchronized (this) {
2655             pw.println("NetworkTranstionWakeLock is currently " +
2656                     (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
2657             pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
2658         }
2659         pw.println();
2660
2661         mTethering.dump(fd, pw, args);
2662
2663         if (mInetLog != null) {
2664             pw.println();
2665             pw.println("Inet condition reports:");
2666             pw.increaseIndent();
2667             for(int i = 0; i < mInetLog.size(); i++) {
2668                 pw.println(mInetLog.get(i));
2669             }
2670             pw.decreaseIndent();
2671         }
2672     }
2673
2674     // must be stateless - things change under us.
2675     private class NetworkStateTrackerHandler extends Handler {
2676         public NetworkStateTrackerHandler(Looper looper) {
2677             super(looper);
2678         }
2679
2680         @Override
2681         public void handleMessage(Message msg) {
2682             NetworkInfo info;
2683             switch (msg.what) {
2684                 case NetworkStateTracker.EVENT_STATE_CHANGED:
2685                     info = (NetworkInfo) msg.obj;
2686                     int type = info.getType();
2687                     NetworkInfo.State state = info.getState();
2688
2689                     if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
2690                             (state == NetworkInfo.State.DISCONNECTED)) {
2691                         log("ConnectivityChange for " +
2692                             info.getTypeName() + ": " +
2693                             state + "/" + info.getDetailedState());
2694                     }
2695
2696                     EventLogTags.writeConnectivityStateChanged(
2697                             info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
2698
2699                     if (info.getDetailedState() ==
2700                             NetworkInfo.DetailedState.FAILED) {
2701                         handleConnectionFailure(info);
2702                     } else if (info.getDetailedState() ==
2703                             DetailedState.CAPTIVE_PORTAL_CHECK) {
2704                         handleCaptivePortalTrackerCheck(info);
2705                     } else if (state == NetworkInfo.State.DISCONNECTED) {
2706                         handleDisconnect(info);
2707                     } else if (state == NetworkInfo.State.SUSPENDED) {
2708                         // TODO: need to think this over.
2709                         // the logic here is, handle SUSPENDED the same as
2710                         // DISCONNECTED. The only difference being we are
2711                         // broadcasting an intent with NetworkInfo that's
2712                         // suspended. This allows the applications an
2713                         // opportunity to handle DISCONNECTED and SUSPENDED
2714                         // differently, or not.
2715                         handleDisconnect(info);
2716                     } else if (state == NetworkInfo.State.CONNECTED) {
2717                         handleConnect(info);
2718                     }
2719                     if (mLockdownTracker != null) {
2720                         mLockdownTracker.onNetworkInfoChanged(info);
2721                     }
2722                     break;
2723                 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED:
2724                     info = (NetworkInfo) msg.obj;
2725                     // TODO: Temporary allowing network configuration
2726                     //       change not resetting sockets.
2727                     //       @see bug/4455071
2728                     handleConnectivityChange(info.getType(), false);
2729                     break;
2730                 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED:
2731                     info = (NetworkInfo) msg.obj;
2732                     type = info.getType();
2733                     updateNetworkSettings(mNetTrackers[type]);
2734                     break;
2735             }
2736         }
2737     }
2738
2739     private class InternalHandler extends Handler {
2740         public InternalHandler(Looper looper) {
2741             super(looper);
2742         }
2743
2744         @Override
2745         public void handleMessage(Message msg) {
2746             NetworkInfo info;
2747             switch (msg.what) {
2748                 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK:
2749                     String causedBy = null;
2750                     synchronized (ConnectivityService.this) {
2751                         if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2752                                 mNetTransitionWakeLock.isHeld()) {
2753                             mNetTransitionWakeLock.release();
2754                             causedBy = mNetTransitionWakeLockCausedBy;
2755                         }
2756                     }
2757                     if (causedBy != null) {
2758                         log("NetTransition Wakelock for " + causedBy + " released by timeout");
2759                     }
2760                     break;
2761                 case EVENT_RESTORE_DEFAULT_NETWORK:
2762                     FeatureUser u = (FeatureUser)msg.obj;
2763                     u.expire();
2764                     break;
2765                 case EVENT_INET_CONDITION_CHANGE:
2766                 {
2767                     int netType = msg.arg1;
2768                     int condition = msg.arg2;
2769                     handleInetConditionChange(netType, condition);
2770                     break;
2771                 }
2772                 case EVENT_INET_CONDITION_HOLD_END:
2773                 {
2774                     int netType = msg.arg1;
2775                     int sequence = msg.arg2;
2776                     handleInetConditionHoldEnd(netType, sequence);
2777                     break;
2778                 }
2779                 case EVENT_SET_NETWORK_PREFERENCE:
2780                 {
2781                     int preference = msg.arg1;
2782                     handleSetNetworkPreference(preference);
2783                     break;
2784                 }
2785                 case EVENT_SET_MOBILE_DATA:
2786                 {
2787                     boolean enabled = (msg.arg1 == ENABLED);
2788                     handleSetMobileData(enabled);
2789                     break;
2790                 }
2791                 case EVENT_APPLY_GLOBAL_HTTP_PROXY:
2792                 {
2793                     handleDeprecatedGlobalHttpProxy();
2794                     break;
2795                 }
2796                 case EVENT_SET_DEPENDENCY_MET:
2797                 {
2798                     boolean met = (msg.arg1 == ENABLED);
2799                     handleSetDependencyMet(msg.arg2, met);
2800                     break;
2801                 }
2802                 case EVENT_RESTORE_DNS:
2803                 {
2804                     if (mActiveDefaultNetwork != -1) {
2805                         handleDnsConfigurationChange(mActiveDefaultNetwork);
2806                     }
2807                     break;
2808                 }
2809                 case EVENT_SEND_STICKY_BROADCAST_INTENT:
2810                 {
2811                     Intent intent = (Intent)msg.obj;
2812                     sendStickyBroadcast(intent);
2813                     break;
2814                 }
2815                 case EVENT_SET_POLICY_DATA_ENABLE: {
2816                     final int networkType = msg.arg1;
2817                     final boolean enabled = msg.arg2 == ENABLED;
2818                     handleSetPolicyDataEnable(networkType, enabled);
2819                     break;
2820                 }
2821                 case EVENT_VPN_STATE_CHANGED: {
2822                     if (mLockdownTracker != null) {
2823                         mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
2824                     }
2825                     break;
2826                 }
2827             }
2828         }
2829     }
2830
2831     // javadoc from interface
2832     public int tether(String iface) {
2833         enforceTetherChangePermission();
2834
2835         if (isTetheringSupported()) {
2836             return mTethering.tether(iface);
2837         } else {
2838             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2839         }
2840     }
2841
2842     // javadoc from interface
2843     public int untether(String iface) {
2844         enforceTetherChangePermission();
2845
2846         if (isTetheringSupported()) {
2847             return mTethering.untether(iface);
2848         } else {
2849             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2850         }
2851     }
2852
2853     // javadoc from interface
2854     public int getLastTetherError(String iface) {
2855         enforceTetherAccessPermission();
2856
2857         if (isTetheringSupported()) {
2858             return mTethering.getLastTetherError(iface);
2859         } else {
2860             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2861         }
2862     }
2863
2864     // TODO - proper iface API for selection by property, inspection, etc
2865     public String[] getTetherableUsbRegexs() {
2866         enforceTetherAccessPermission();
2867         if (isTetheringSupported()) {
2868             return mTethering.getTetherableUsbRegexs();
2869         } else {
2870             return new String[0];
2871         }
2872     }
2873
2874     public String[] getTetherableWifiRegexs() {
2875         enforceTetherAccessPermission();
2876         if (isTetheringSupported()) {
2877             return mTethering.getTetherableWifiRegexs();
2878         } else {
2879             return new String[0];
2880         }
2881     }
2882
2883     public String[] getTetherableBluetoothRegexs() {
2884         enforceTetherAccessPermission();
2885         if (isTetheringSupported()) {
2886             return mTethering.getTetherableBluetoothRegexs();
2887         } else {
2888             return new String[0];
2889         }
2890     }
2891
2892     public int setUsbTethering(boolean enable) {
2893         enforceTetherChangePermission();
2894         if (isTetheringSupported()) {
2895             return mTethering.setUsbTethering(enable);
2896         } else {
2897             return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2898         }
2899     }
2900
2901     // TODO - move iface listing, queries, etc to new module
2902     // javadoc from interface
2903     public String[] getTetherableIfaces() {
2904         enforceTetherAccessPermission();
2905         return mTethering.getTetherableIfaces();
2906     }
2907
2908     public String[] getTetheredIfaces() {
2909         enforceTetherAccessPermission();
2910         return mTethering.getTetheredIfaces();
2911     }
2912
2913     @Override
2914     public String[] getTetheredIfacePairs() {
2915         enforceTetherAccessPermission();
2916         return mTethering.getTetheredIfacePairs();
2917     }
2918
2919     public String[] getTetheringErroredIfaces() {
2920         enforceTetherAccessPermission();
2921         return mTethering.getErroredIfaces();
2922     }
2923
2924     // if ro.tether.denied = true we default to no tethering
2925     // gservices could set the secure setting to 1 though to enable it on a build where it
2926     // had previously been turned off.
2927     public boolean isTetheringSupported() {
2928         enforceTetherAccessPermission();
2929         int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2930         boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2931                 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
2932         return tetherEnabledInSettings && mTetheringConfigValid;
2933     }
2934
2935     // An API NetworkStateTrackers can call when they lose their network.
2936     // This will automatically be cleared after X seconds or a network becomes CONNECTED,
2937     // whichever happens first.  The timer is started by the first caller and not
2938     // restarted by subsequent callers.
2939     public void requestNetworkTransitionWakelock(String forWhom) {
2940         enforceConnectivityInternalPermission();
2941         synchronized (this) {
2942             if (mNetTransitionWakeLock.isHeld()) return;
2943             mNetTransitionWakeLockSerialNumber++;
2944             mNetTransitionWakeLock.acquire();
2945             mNetTransitionWakeLockCausedBy = forWhom;
2946         }
2947         mHandler.sendMessageDelayed(mHandler.obtainMessage(
2948                 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
2949                 mNetTransitionWakeLockSerialNumber, 0),
2950                 mNetTransitionWakeLockTimeout);
2951         return;
2952     }
2953
2954     // 100 percent is full good, 0 is full bad.
2955     public void reportInetCondition(int networkType, int percentage) {
2956         if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
2957         mContext.enforceCallingOrSelfPermission(
2958                 android.Manifest.permission.STATUS_BAR,
2959                 "ConnectivityService");
2960
2961         if (DBG) {
2962             int pid = getCallingPid();
2963             int uid = getCallingUid();
2964             String s = pid + "(" + uid + ") reports inet is " +
2965                 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
2966                 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
2967             mInetLog.add(s);
2968             while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
2969                 mInetLog.remove(0);
2970             }
2971         }
2972         mHandler.sendMessage(mHandler.obtainMessage(
2973             EVENT_INET_CONDITION_CHANGE, networkType, percentage));
2974     }
2975
2976     private void handleInetConditionChange(int netType, int condition) {
2977         if (mActiveDefaultNetwork == -1) {
2978             if (DBG) log("handleInetConditionChange: no active default network - ignore");
2979             return;
2980         }
2981         if (mActiveDefaultNetwork != netType) {
2982             if (DBG) log("handleInetConditionChange: net=" + netType +
2983                             " != default=" + mActiveDefaultNetwork + " - ignore");
2984             return;
2985         }
2986         if (VDBG) {
2987             log("handleInetConditionChange: net=" +
2988                     netType + ", condition=" + condition +
2989                     ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
2990         }
2991         mDefaultInetCondition = condition;
2992         int delay;
2993         if (mInetConditionChangeInFlight == false) {
2994             if (VDBG) log("handleInetConditionChange: starting a change hold");
2995             // setup a new hold to debounce this
2996             if (mDefaultInetCondition > 50) {
2997                 delay = Settings.Global.getInt(mContext.getContentResolver(),
2998                         Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
2999             } else {
3000                 delay = Settings.Global.getInt(mContext.getContentResolver(),
3001                         Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
3002             }
3003             mInetConditionChangeInFlight = true;
3004             mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
3005                     mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
3006         } else {
3007             // we've set the new condition, when this hold ends that will get picked up
3008             if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
3009         }
3010     }
3011
3012     private void handleInetConditionHoldEnd(int netType, int sequence) {
3013         if (DBG) {
3014             log("handleInetConditionHoldEnd: net=" + netType +
3015                     ", condition=" + mDefaultInetCondition +
3016                     ", published condition=" + mDefaultInetConditionPublished);
3017         }
3018         mInetConditionChangeInFlight = false;
3019
3020         if (mActiveDefaultNetwork == -1) {
3021             if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
3022             return;
3023         }
3024         if (mDefaultConnectionSequence != sequence) {
3025             if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
3026             return;
3027         }
3028         // TODO: Figure out why this optimization sometimes causes a
3029         //       change in mDefaultInetCondition to be missed and the
3030         //       UI to not be updated.
3031         //if (mDefaultInetConditionPublished == mDefaultInetCondition) {
3032         //    if (DBG) log("no change in condition - aborting");
3033         //    return;
3034         //}
3035         NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
3036         if (networkInfo.isConnected() == false) {
3037             if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
3038             return;
3039         }
3040         mDefaultInetConditionPublished = mDefaultInetCondition;
3041         sendInetConditionBroadcast(networkInfo);
3042         return;
3043     }
3044
3045     public ProxyProperties getProxy() {
3046         // this information is already available as a world read/writable jvm property
3047         // so this API change wouldn't have a benifit.  It also breaks the passing
3048         // of proxy info to all the JVMs.
3049         // enforceAccessPermission();
3050         synchronized (mProxyLock) {
3051             if (mGlobalProxy != null) return mGlobalProxy;
3052             return (mDefaultProxyDisabled ? null : mDefaultProxy);
3053         }
3054     }
3055
3056     public void setGlobalProxy(ProxyProperties proxyProperties) {
3057         enforceConnectivityInternalPermission();
3058         synchronized (mProxyLock) {
3059             if (proxyProperties == mGlobalProxy) return;
3060             if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3061             if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3062
3063             String host = "";
3064             int port = 0;
3065             String exclList = "";
3066             if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) {
3067                 mGlobalProxy = new ProxyProperties(proxyProperties);
3068                 host = mGlobalProxy.getHost();
3069                 port = mGlobalProxy.getPort();
3070                 exclList = mGlobalProxy.getExclusionList();
3071             } else {
3072                 mGlobalProxy = null;
3073             }
3074             ContentResolver res = mContext.getContentResolver();
3075             final long token = Binder.clearCallingIdentity();
3076             try {
3077                 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3078                 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3079                 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3080                         exclList);
3081             } finally {
3082                 Binder.restoreCallingIdentity(token);
3083             }
3084         }
3085
3086         if (mGlobalProxy == null) {
3087             proxyProperties = mDefaultProxy;
3088         }
3089         sendProxyBroadcast(proxyProperties);
3090     }
3091
3092     private void loadGlobalProxy() {
3093         ContentResolver res = mContext.getContentResolver();
3094         String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3095         int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3096         String exclList = Settings.Global.getString(res,
3097                 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3098         if (!TextUtils.isEmpty(host)) {
3099             ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList);
3100             synchronized (mProxyLock) {
3101                 mGlobalProxy = proxyProperties;
3102             }
3103         }
3104     }
3105
3106     public ProxyProperties getGlobalProxy() {
3107         // this information is already available as a world read/writable jvm property
3108         // so this API change wouldn't have a benifit.  It also breaks the passing
3109         // of proxy info to all the JVMs.
3110         // enforceAccessPermission();
3111         synchronized (mProxyLock) {
3112             return mGlobalProxy;
3113         }
3114     }
3115
3116     private void handleApplyDefaultProxy(ProxyProperties proxy) {
3117         if (proxy != null && TextUtils.isEmpty(proxy.getHost())) {
3118             proxy = null;
3119         }
3120         synchronized (mProxyLock) {
3121             if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3122             if (mDefaultProxy == proxy) return; // catches repeated nulls
3123             mDefaultProxy = proxy;
3124
3125             if (mGlobalProxy != null) return;
3126             if (!mDefaultProxyDisabled) {
3127                 sendProxyBroadcast(proxy);
3128             }
3129         }
3130     }
3131
3132     private void handleDeprecatedGlobalHttpProxy() {
3133         String proxy = Settings.Global.getString(mContext.getContentResolver(),
3134                 Settings.Global.HTTP_PROXY);
3135         if (!TextUtils.isEmpty(proxy)) {
3136             String data[] = proxy.split(":");
3137             String proxyHost =  data[0];
3138             int proxyPort = 8080;
3139             if (data.length > 1) {
3140                 try {
3141                     proxyPort = Integer.parseInt(data[1]);
3142                 } catch (NumberFormatException e) {
3143                     return;
3144                 }
3145             }
3146             ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
3147             setGlobalProxy(p);
3148         }
3149     }
3150
3151     private void sendProxyBroadcast(ProxyProperties proxy) {
3152         if (proxy == null) proxy = new ProxyProperties("", 0, "");
3153         if (DBG) log("sending Proxy Broadcast for " + proxy);
3154         Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3155         intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3156             Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3157         intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3158         final long ident = Binder.clearCallingIdentity();
3159         try {
3160             mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3161         } finally {
3162             Binder.restoreCallingIdentity(ident);
3163         }
3164     }
3165
3166     private static class SettingsObserver extends ContentObserver {
3167         private int mWhat;
3168         private Handler mHandler;
3169         SettingsObserver(Handler handler, int what) {
3170             super(handler);
3171             mHandler = handler;
3172             mWhat = what;
3173         }
3174
3175         void observe(Context context) {
3176             ContentResolver resolver = context.getContentResolver();
3177             resolver.registerContentObserver(Settings.Global.getUriFor(
3178                     Settings.Global.HTTP_PROXY), false, this);
3179         }
3180
3181         @Override
3182         public void onChange(boolean selfChange) {
3183             mHandler.obtainMessage(mWhat).sendToTarget();
3184         }
3185     }
3186
3187     private static void log(String s) {
3188         Slog.d(TAG, s);
3189     }
3190
3191     private static void loge(String s) {
3192         Slog.e(TAG, s);
3193     }
3194
3195     int convertFeatureToNetworkType(int networkType, String feature) {
3196         int usedNetworkType = networkType;
3197
3198         if(networkType == ConnectivityManager.TYPE_MOBILE) {
3199             if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
3200                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
3201             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
3202                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
3203             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
3204                     TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
3205                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
3206             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
3207                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
3208             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
3209                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
3210             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
3211                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
3212             } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
3213                 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
3214             } else {
3215                 Slog.e(TAG, "Can't match any mobile netTracker!");
3216             }
3217         } else if (networkType == ConnectivityManager.TYPE_WIFI) {
3218             if (TextUtils.equals(feature, "p2p")) {
3219                 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
3220             } else {
3221                 Slog.e(TAG, "Can't match any wifi netTracker!");
3222             }
3223         } else {
3224             Slog.e(TAG, "Unexpected network type");
3225         }
3226         return usedNetworkType;
3227     }
3228
3229     private static <T> T checkNotNull(T value, String message) {
3230         if (value == null) {
3231             throw new NullPointerException(message);
3232         }
3233         return value;
3234     }
3235
3236     /**
3237      * Protect a socket from VPN routing rules. This method is used by
3238      * VpnBuilder and not available in ConnectivityManager. Permissions
3239      * are checked in Vpn class.
3240      * @hide
3241      */
3242     @Override
3243     public boolean protectVpn(ParcelFileDescriptor socket) {
3244         throwIfLockdownEnabled();
3245         try {
3246             int type = mActiveDefaultNetwork;
3247             if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
3248                 mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
3249                 return true;
3250             }
3251         } catch (Exception e) {
3252             // ignore
3253         } finally {
3254             try {
3255                 socket.close();
3256             } catch (Exception e) {
3257                 // ignore
3258             }
3259         }
3260         return false;
3261     }
3262
3263     /**
3264      * Prepare for a VPN application. This method is used by VpnDialogs
3265      * and not available in ConnectivityManager. Permissions are checked
3266      * in Vpn class.
3267      * @hide
3268      */
3269     @Override
3270     public boolean prepareVpn(String oldPackage, String newPackage) {
3271         throwIfLockdownEnabled();
3272         return mVpn.prepare(oldPackage, newPackage);
3273     }
3274
3275     /**
3276      * Configure a TUN interface and return its file descriptor. Parameters
3277      * are encoded and opaque to this class. This method is used by VpnBuilder
3278      * and not available in ConnectivityManager. Permissions are checked in
3279      * Vpn class.
3280      * @hide
3281      */
3282     @Override
3283     public ParcelFileDescriptor establishVpn(VpnConfig config) {
3284         throwIfLockdownEnabled();
3285         return mVpn.establish(config);
3286     }
3287
3288     /**
3289      * Start legacy VPN, controlling native daemons as needed. Creates a
3290      * secondary thread to perform connection work, returning quickly.
3291      */
3292     @Override
3293     public void startLegacyVpn(VpnProfile profile) {
3294         throwIfLockdownEnabled();
3295         final LinkProperties egress = getActiveLinkProperties();
3296         if (egress == null) {
3297             throw new IllegalStateException("Missing active network connection");
3298         }
3299         mVpn.startLegacyVpn(profile, mKeyStore, egress);
3300     }
3301
3302     /**
3303      * Return the information of the ongoing legacy VPN. This method is used
3304      * by VpnSettings and not available in ConnectivityManager. Permissions
3305      * are checked in Vpn class.
3306      * @hide
3307      */
3308     @Override
3309     public LegacyVpnInfo getLegacyVpnInfo() {
3310         throwIfLockdownEnabled();
3311         return mVpn.getLegacyVpnInfo();
3312     }
3313
3314     /**
3315      * Callback for VPN subsystem. Currently VPN is not adapted to the service
3316      * through NetworkStateTracker since it works differently. For example, it
3317      * needs to override DNS servers but never takes the default routes. It
3318      * relies on another data network, and it could keep existing connections
3319      * alive after reconnecting, switching between networks, or even resuming
3320      * from deep sleep. Calls from applications should be done synchronously
3321      * to avoid race conditions. As these are all hidden APIs, refactoring can
3322      * be done whenever a better abstraction is developed.
3323      */
3324     public class VpnCallback {
3325         private VpnCallback() {
3326         }
3327
3328         public void onStateChanged(NetworkInfo info) {
3329             mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
3330         }
3331
3332         public void override(List<String> dnsServers, List<String> searchDomains) {
3333             if (dnsServers == null) {
3334                 restore();
3335                 return;
3336             }
3337
3338             // Convert DNS servers into addresses.
3339             List<InetAddress> addresses = new ArrayList<InetAddress>();
3340             for (String address : dnsServers) {
3341                 // Double check the addresses and remove invalid ones.
3342                 try {
3343                     addresses.add(InetAddress.parseNumericAddress(address));
3344                 } catch (Exception e) {
3345                     // ignore
3346                 }
3347             }
3348             if (addresses.isEmpty()) {
3349                 restore();
3350                 return;
3351             }
3352
3353             // Concatenate search domains into a string.
3354             StringBuilder buffer = new StringBuilder();
3355             if (searchDomains != null) {
3356                 for (String domain : searchDomains) {
3357                     buffer.append(domain).append(' ');
3358                 }
3359             }
3360             String domains = buffer.toString().trim();
3361
3362             // Apply DNS changes.
3363             synchronized (mDnsLock) {
3364                 updateDnsLocked("VPN", "VPN", addresses, domains);
3365                 mDnsOverridden = true;
3366             }
3367
3368             // Temporarily disable the default proxy (not global).
3369             synchronized (mProxyLock) {
3370                 mDefaultProxyDisabled = true;
3371                 if (mGlobalProxy == null && mDefaultProxy != null) {
3372                     sendProxyBroadcast(null);
3373                 }
3374             }
3375
3376             // TODO: support proxy per network.
3377         }
3378
3379         public void restore() {
3380             synchronized (mDnsLock) {
3381                 if (mDnsOverridden) {
3382                     mDnsOverridden = false;
3383                     mHandler.sendEmptyMessage(EVENT_RESTORE_DNS);
3384                 }
3385             }
3386             synchronized (mProxyLock) {
3387                 mDefaultProxyDisabled = false;
3388                 if (mGlobalProxy == null && mDefaultProxy != null) {
3389                     sendProxyBroadcast(mDefaultProxy);
3390                 }
3391             }
3392         }
3393     }
3394
3395     @Override
3396     public boolean updateLockdownVpn() {
3397         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3398             Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3399             return false;
3400         }
3401
3402         // Tear down existing lockdown if profile was removed
3403         mLockdownEnabled = LockdownVpnTracker.isEnabled();
3404         if (mLockdownEnabled) {
3405             if (!mKeyStore.isUnlocked()) {
3406                 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3407                 return false;
3408             }
3409
3410             final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3411             final VpnProfile profile = VpnProfile.decode(
3412                     profileName, mKeyStore.get(Credentials.VPN + profileName));
3413             setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpn, profile));
3414         } else {
3415             setLockdownTracker(null);
3416         }
3417
3418         return true;
3419     }
3420
3421     /**
3422      * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3423      * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3424      */
3425     private void setLockdownTracker(LockdownVpnTracker tracker) {
3426         // Shutdown any existing tracker
3427         final LockdownVpnTracker existing = mLockdownTracker;
3428         mLockdownTracker = null;
3429         if (existing != null) {
3430             existing.shutdown();
3431         }
3432
3433         try {
3434             if (tracker != null) {
3435                 mNetd.setFirewallEnabled(true);
3436                 mNetd.setFirewallInterfaceRule("lo", true);
3437                 mLockdownTracker = tracker;
3438                 mLockdownTracker.init();
3439             } else {
3440                 mNetd.setFirewallEnabled(false);
3441             }
3442         } catch (RemoteException e) {
3443             // ignored; NMS lives inside system_server
3444         }
3445     }
3446
3447     private void throwIfLockdownEnabled() {
3448         if (mLockdownEnabled) {
3449             throw new IllegalStateException("Unavailable in lockdown mode");
3450         }
3451     }
3452
3453     public void supplyMessenger(int networkType, Messenger messenger) {
3454         enforceConnectivityInternalPermission();
3455
3456         if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
3457             mNetTrackers[networkType].supplyMessenger(messenger);
3458         }
3459     }
3460
3461     public int findConnectionTypeForIface(String iface) {
3462         enforceConnectivityInternalPermission();
3463
3464         if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
3465         for (NetworkStateTracker tracker : mNetTrackers) {
3466             if (tracker != null) {
3467                 LinkProperties lp = tracker.getLinkProperties();
3468                 if (lp != null && iface.equals(lp.getInterfaceName())) {
3469                     return tracker.getNetworkInfo().getType();
3470                 }
3471             }
3472         }
3473         return ConnectivityManager.TYPE_NONE;
3474     }
3475 }