OSDN Git Service

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