Remove dead code 4.

Removing:
handleDnsConfigurationChange
updateDnsLocked
updateRoutes
handleConnectivityChange
handleConnect
handleDisconnect

Adding a missing flushVmDnsCache and setting of mActiveDefaultNetwork

Change-Id: I681fc72c317833ea1deb42db0b43d2adb21baeff
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index cc2167d..7aa69fd 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -1296,172 +1296,6 @@
                 "ConnectivityService");
     }
 
-    /**
-     * Handle a {@code DISCONNECTED} event. If this pertains to the non-active
-     * network, we ignore it. If it is for the active network, we send out a
-     * broadcast. But first, we check whether it might be possible to connect
-     * to a different network.
-     * @param info the {@code NetworkInfo} for the network
-     */
-    private void handleDisconnect(NetworkInfo info) {
-
-        int prevNetType = info.getType();
-
-        mNetTrackers[prevNetType].setTeardownRequested(false);
-        int thisNetId = mNetTrackers[prevNetType].getNetwork().netId;
-
-        // Remove idletimer previously setup in {@code handleConnect}
-// Already in place in new function. This is dead code.
-//        if (mNetConfigs[prevNetType].isDefault()) {
-//            removeDataActivityTracking(prevNetType);
-//        }
-
-        /*
-         * If the disconnected network is not the active one, then don't report
-         * this as a loss of connectivity. What probably happened is that we're
-         * getting the disconnect for a network that we explicitly disabled
-         * in accordance with network preference policies.
-         */
-//        if (!mNetConfigs[prevNetType].isDefault()) {
-//            List<Integer> pids = mNetRequestersPids[prevNetType];
-//            for (Integer pid : pids) {
-//                // will remove them because the net's no longer connected
-//                // need to do this now as only now do we know the pids and
-//                // can properly null things that are no longer referenced.
-//                reassessPidDns(pid.intValue(), false);
-//            }
-//        }
-
-        Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
-        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
-        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
-        if (info.isFailover()) {
-            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
-            info.setFailover(false);
-        }
-        if (info.getReason() != null) {
-            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
-        }
-        if (info.getExtraInfo() != null) {
-            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
-                    info.getExtraInfo());
-        }
-
-        if (mNetConfigs[prevNetType].isDefault()) {
-            tryFailover(prevNetType);
-            if (mActiveDefaultNetwork != -1) {
-                NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
-                intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
-            } else {
-                mDefaultInetConditionPublished = 0; // we're not connected anymore
-                intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
-            }
-        }
-        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
-
-        // Reset interface if no other connections are using the same interface
-        boolean doReset = true;
-        LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
-        if (linkProperties != null) {
-            String oldIface = linkProperties.getInterfaceName();
-            if (TextUtils.isEmpty(oldIface) == false) {
-                for (NetworkStateTracker networkStateTracker : mNetTrackers) {
-                    if (networkStateTracker == null) continue;
-                    NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
-                    if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
-                        LinkProperties l = networkStateTracker.getLinkProperties();
-                        if (l == null) continue;
-                        if (oldIface.equals(l.getInterfaceName())) {
-                            doReset = false;
-                            break;
-                        }
-                    }
-                }
-            }
-        }
-
-        // do this before we broadcast the change
-// Already done in new function. This is dead code.
-//        handleConnectivityChange(prevNetType, doReset);
-
-        final Intent immediateIntent = new Intent(intent);
-        immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
-        sendStickyBroadcast(immediateIntent);
-        sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
-        /*
-         * If the failover network is already connected, then immediately send
-         * out a followup broadcast indicating successful failover
-         */
-        if (mActiveDefaultNetwork != -1) {
-            sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
-                    getConnectivityChangeDelay());
-        }
-        try {
-//            mNetd.removeNetwork(thisNetId);
-        } catch (Exception e) {
-            loge("Exception removing network: " + e);
-        } finally {
-//            mNetTrackers[prevNetType].setNetId(INVALID_NET_ID);
-        }
-    }
-
-    private void tryFailover(int prevNetType) {
-        /*
-         * If this is a default network, check if other defaults are available.
-         * Try to reconnect on all available and let them hash it out when
-         * more than one connects.
-         */
-        if (mNetConfigs[prevNetType].isDefault()) {
-            if (mActiveDefaultNetwork == prevNetType) {
-                if (DBG) {
-                    log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
-                }
-                mActiveDefaultNetwork = -1;
-                try {
-                    mNetd.clearDefaultNetId();
-                } catch (Exception e) {
-                    loge("Exception clearing default network :" + e);
-                }
-            }
-
-            // don't signal a reconnect for anything lower or equal priority than our
-            // current connected default
-            // TODO - don't filter by priority now - nice optimization but risky
-//            int currentPriority = -1;
-//            if (mActiveDefaultNetwork != -1) {
-//                currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
-//            }
-
-            for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
-                if (checkType == prevNetType) continue;
-                if (mNetConfigs[checkType] == null) continue;
-                if (!mNetConfigs[checkType].isDefault()) continue;
-                if (mNetTrackers[checkType] == null) continue;
-
-// Enabling the isAvailable() optimization caused mobile to not get
-// selected if it was in the middle of error handling. Specifically
-// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
-// would not be available and we wouldn't get connected to anything.
-// So removing the isAvailable() optimization below for now. TODO: This
-// optimization should work and we need to investigate why it doesn't work.
-// This could be related to how DEACTIVATE_DATA_CALL is reporting its
-// complete before it is really complete.
-
-//                if (!mNetTrackers[checkType].isAvailable()) continue;
-
-//                if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
-
-                NetworkStateTracker checkTracker = mNetTrackers[checkType];
-                NetworkInfo checkInfo = checkTracker.getNetworkInfo();
-                if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
-                    checkInfo.setFailover(true);
-                    checkTracker.reconnect();
-                }
-                if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
-            }
-        }
-    }
-
     public void sendConnectedBroadcast(NetworkInfo info) {
         enforceConnectivityInternalPermission();
         sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
@@ -1597,125 +1431,6 @@
         }
     };
 
-    private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
-        if (((type != mNetworkPreference)
-                      && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
-                   || (mNetworkPreference == mActiveDefaultNetwork)) {
-            return false;
-        }
-        return true;
-    }
-
-    private void handleConnect(NetworkInfo info) {
-        final int newNetType = info.getType();
-
-        // snapshot isFailover, because sendConnectedBroadcast() resets it
-        boolean isFailover = info.isFailover();
-        final NetworkStateTracker thisNet = mNetTrackers[newNetType];
-        final String thisIface = thisNet.getLinkProperties().getInterfaceName();
-
-        if (VDBG) {
-            log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
-                    + " isFailover" + isFailover);
-        }
-
-        // if this is a default net and other default is running
-        // kill the one not preferred
-        if (mNetConfigs[newNetType].isDefault()) {
-            if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
-                if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
-                   String teardownPolicy = SystemProperties.get("net.teardownPolicy");
-                   if (TextUtils.equals(teardownPolicy, "keep") == false) {
-                        // tear down the other
-                        NetworkStateTracker otherNet =
-                                mNetTrackers[mActiveDefaultNetwork];
-                        if (DBG) {
-                            log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
-                                " teardown");
-                        }
-                        if (!teardown(otherNet)) {
-                            loge("Network declined teardown request");
-                            teardown(thisNet);
-                            return;
-                        }
-                    } else {
-                        //TODO - remove
-                        loge("network teardown skipped due to net.teardownPolicy setting");
-                    }
-                } else {
-                       // don't accept this one
-                        if (VDBG) {
-                            log("Not broadcasting CONNECT_ACTION " +
-                                "to torn down network " + info.getTypeName());
-                        }
-                        teardown(thisNet);
-                        return;
-                }
-            }
-            int thisNetId = nextNetId();
-            thisNet.setNetId(thisNetId);
-            try {
-//                mNetd.createNetwork(thisNetId, thisIface);
-            } catch (Exception e) {
-                loge("Exception creating network :" + e);
-                teardown(thisNet);
-                return;
-            }
-// Already in place in new function. This is dead code.
-//            setupDataActivityTracking(newNetType);
-            synchronized (ConnectivityService.this) {
-                // have a new default network, release the transition wakelock in a second
-                // if it's held.  The second pause is to allow apps to reconnect over the
-                // new network
-                if (mNetTransitionWakeLock.isHeld()) {
-                    mHandler.sendMessageDelayed(mHandler.obtainMessage(
-                            EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
-                            mNetTransitionWakeLockSerialNumber, 0),
-                            1000);
-                }
-            }
-            mActiveDefaultNetwork = newNetType;
-            try {
-                mNetd.setDefaultNetId(thisNetId);
-            } catch (Exception e) {
-                loge("Exception setting default network :" + e);
-            }
-            // this will cause us to come up initially as unconnected and switching
-            // to connected after our normal pause unless somebody reports us as reall
-            // disconnected
-            mDefaultInetConditionPublished = 0;
-            mDefaultConnectionSequence++;
-            mInetConditionChangeInFlight = false;
-            // Don't do this - if we never sign in stay, grey
-            //reportNetworkCondition(mActiveDefaultNetwork, 100);
-            updateNetworkSettings(thisNet);
-        } else {
-            int thisNetId = nextNetId();
-            thisNet.setNetId(thisNetId);
-            try {
-//                mNetd.createNetwork(thisNetId, thisIface);
-            } catch (Exception e) {
-                loge("Exception creating network :" + e);
-                teardown(thisNet);
-                return;
-            }
-        }
-        thisNet.setTeardownRequested(false);
-// Already in place in new function. This is dead code.
-//        updateMtuSizeSettings(thisNet);
-//        handleConnectivityChange(newNetType, false);
-        sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
-
-        // notify battery stats service about this network
-        if (thisIface != null) {
-            try {
-                BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
-            } catch (RemoteException e) {
-                // ignored; service lives in system_server
-            }
-        }
-    }
-
     /** @hide */
     @Override
     public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
@@ -1782,199 +1497,6 @@
     }
 
     /**
-     * After a change in the connectivity state of a network. We're mainly
-     * concerned with making sure that the list of DNS servers is set up
-     * according to which networks are connected, and ensuring that the
-     * right routing table entries exist.
-     *
-     * TODO - delete when we're sure all this functionallity is captured.
-     */
-    /*
-    private void handleConnectivityChange(int netType, LinkProperties curLp, boolean doReset) {
-        int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
-        boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
-        if (VDBG) {
-            log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
-                    + " resetMask=" + resetMask);
-        }
-
-        // If a non-default network is enabled, add the host routes that
-        // will allow it's DNS servers to be accessed.
-        handleDnsConfigurationChange(netType);
-
-        LinkProperties newLp = null;
-
-        if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
-            newLp = mNetTrackers[netType].getLinkProperties();
-            if (VDBG) {
-                log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
-                        " doReset=" + doReset + " resetMask=" + resetMask +
-                        "\n   curLp=" + curLp +
-                        "\n   newLp=" + newLp);
-            }
-
-            if (curLp != null) {
-                if (curLp.isIdenticalInterfaceName(newLp)) {
-                    CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
-                    if ((car.removed.size() != 0) || (car.added.size() != 0)) {
-                        for (LinkAddress linkAddr : car.removed) {
-                            if (linkAddr.getAddress() instanceof Inet4Address) {
-                                resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
-                            }
-                            if (linkAddr.getAddress() instanceof Inet6Address) {
-                                resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
-                            }
-                        }
-                        if (DBG) {
-                            log("handleConnectivityChange: addresses changed" +
-                                    " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
-                                    "\n   car=" + car);
-                        }
-                    } else {
-                        if (VDBG) {
-                            log("handleConnectivityChange: addresses are the same reset per" +
-                                   " doReset linkProperty[" + netType + "]:" +
-                                   " resetMask=" + resetMask);
-                        }
-                    }
-                } else {
-                    resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
-                    if (DBG) {
-                        log("handleConnectivityChange: interface not not equivalent reset both" +
-                                " linkProperty[" + netType + "]:" +
-                                " resetMask=" + resetMask);
-                    }
-                }
-            }
-            if (mNetConfigs[netType].isDefault()) {
-                handleApplyDefaultProxy(newLp.getHttpProxy());
-            }
-        } else {
-            if (VDBG) {
-                log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
-                        " doReset=" + doReset + " resetMask=" + resetMask +
-                        "\n  curLp=" + curLp +
-                        "\n  newLp= null");
-            }
-        }
-        mCurrentLinkProperties[netType] = newLp;
-        boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt,
-                                        mNetTrackers[netType].getNetwork().netId);
-
-        if (resetMask != 0 || resetDns) {
-            if (VDBG) log("handleConnectivityChange: resetting");
-            if (curLp != null) {
-                if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
-                for (String iface : curLp.getAllInterfaceNames()) {
-                    if (TextUtils.isEmpty(iface) == false) {
-                        if (resetMask != 0) {
-                            if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
-                            NetworkUtils.resetConnections(iface, resetMask);
-
-                            // Tell VPN the interface is down. It is a temporary
-                            // but effective fix to make VPN aware of the change.
-                            if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
-                                synchronized(mVpns) {
-                                    for (int i = 0; i < mVpns.size(); i++) {
-                                        mVpns.valueAt(i).interfaceStatusChanged(iface, false);
-                                    }
-                                }
-                            }
-                        }
-                    } else {
-                        loge("Can't reset connection for type "+netType);
-                    }
-                }
-                if (resetDns) {
-                    flushVmDnsCache();
-                    if (VDBG) log("resetting DNS cache for type " + netType);
-                    try {
-                        mNetd.flushNetworkDnsCache(mNetTrackers[netType].getNetwork().netId);
-                    } catch (Exception e) {
-                        // never crash - catch them all
-                        if (DBG) loge("Exception resetting dns cache: " + e);
-                    }
-                }
-            }
-        }
-
-        // TODO: Temporary notifying upstread change to Tethering.
-        //       @see bug/4455071
-        //  Notify TetheringService if interface name has been changed.
-        if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
-                             PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
-            if (isTetheringSupported()) {
-                mTethering.handleTetherIfaceChange();
-            }
-        }
-    }
-    */
-
-    /**
-     * Add and remove routes using the old properties (null if not previously connected),
-     * new properties (null if becoming disconnected).  May even be double null, which
-     * is a noop.
-     * Uses isLinkDefault to determine if default routes should be set or conversely if
-     * host routes should be set to the dns servers
-     * returns a boolean indicating the routes changed
-     */
-    /*
-    private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
-            boolean isLinkDefault, boolean exempt, int netId) {
-        Collection<RouteInfo> routesToAdd = null;
-        CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
-        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
-        if (curLp != null) {
-            // check for the delta between the current set and the new
-            routeDiff = curLp.compareAllRoutes(newLp);
-            dnsDiff = curLp.compareDnses(newLp);
-        } else if (newLp != null) {
-            routeDiff.added = newLp.getAllRoutes();
-            dnsDiff.added = newLp.getDnsServers();
-        }
-
-        boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
-
-        for (RouteInfo r : routeDiff.removed) {
-            if (isLinkDefault || ! r.isDefaultRoute()) {
-                if (VDBG) log("updateRoutes: default remove route r=" + r);
-                removeRoute(curLp, r, TO_DEFAULT_TABLE, netId);
-            }
-            if (isLinkDefault == false) {
-                // remove from a secondary route table
-                removeRoute(curLp, r, TO_SECONDARY_TABLE, netId);
-            }
-        }
-
-        for (RouteInfo r :  routeDiff.added) {
-            if (isLinkDefault || ! r.isDefaultRoute()) {
-                addRoute(newLp, r, TO_DEFAULT_TABLE, exempt, netId);
-            } else {
-                // add to a secondary route table
-                addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT, netId);
-
-                // many radios add a default route even when we don't want one.
-                // remove the default route unless somebody else has asked for it
-                String ifaceName = newLp.getInterfaceName();
-                synchronized (mRoutesLock) {
-                    if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
-                        if (VDBG) log("Removing " + r + " for interface " + ifaceName);
-                        try {
-                            mNetd.removeRoute(netId, r);
-                        } catch (Exception e) {
-                            // never crash - catch them all
-                            if (DBG) loge("Exception trying to remove a route: " + e);
-                        }
-                    }
-                }
-            }
-        }
-
-        return routesChanged;
-    }
-    */
-
-    /**
      * Reads the network specific MTU size from reources.
      * and set it on it's iface.
      */
@@ -2080,72 +1602,6 @@
         }
     }
 
-    // Caller must grab mDnsLock.
-    private void updateDnsLocked(String network, int netId,
-            Collection<InetAddress> dnses, String domains) {
-        int last = 0;
-        if (dnses.size() == 0 && mDefaultDns != null) {
-            dnses = new ArrayList();
-            dnses.add(mDefaultDns);
-            if (DBG) {
-                loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
-            }
-        }
-
-        try {
-            mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), domains);
-
-            for (InetAddress dns : dnses) {
-                ++last;
-                String key = "net.dns" + last;
-                String value = dns.getHostAddress();
-                SystemProperties.set(key, value);
-            }
-            for (int i = last + 1; i <= mNumDnsEntries; ++i) {
-                String key = "net.dns" + i;
-                SystemProperties.set(key, "");
-            }
-            mNumDnsEntries = last;
-        } catch (Exception e) {
-            loge("exception setting default dns interface: " + e);
-        }
-    }
-
-    private void handleDnsConfigurationChange(int netType) {
-        // add default net's dns entries
-        NetworkStateTracker nt = mNetTrackers[netType];
-        if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
-            LinkProperties p = nt.getLinkProperties();
-            if (p == null) return;
-            Collection<InetAddress> dnses = p.getDnsServers();
-            int netId = nt.getNetwork().netId;
-            if (mNetConfigs[netType].isDefault()) {
-                String network = nt.getNetworkInfo().getTypeName();
-                synchronized (mDnsLock) {
-                    updateDnsLocked(network, netId, dnses, p.getDomains());
-                }
-            } else {
-                try {
-                    mNetd.setDnsServersForNetwork(netId,
-                            NetworkUtils.makeStrings(dnses), p.getDomains());
-                } catch (Exception e) {
-                    if (DBG) loge("exception setting dns servers: " + e);
-                }
-                // set per-pid dns for attached secondary nets
-//                List<Integer> pids = mNetRequestersPids[netType];
-//                for (Integer pid : pids) {
-//                    try {
-                        // TODO: Reimplement this via local variable in bionic.
-                        // mNetd.setDnsNetworkForPid(netId, pid);
-//                    } catch (Exception e) {
-//                        Slog.e(TAG, "exception setting interface for pid: " + e);
-//                    }
-//                }
-            }
-            flushVmDnsCache();
-        }
-    }
-
     @Override
     public int getRestoreDefaultNetworkDelay(int networkType) {
         String restoreDefaultNetworkDelayStr = SystemProperties.get(
@@ -4829,6 +4285,7 @@
             if (defaultNai != null && defaultNai.network.netId == netId) {
                 setDefaultDnsSystemProperties(dnses);
             }
+            flushVmDnsCache();
         }
     }
 
@@ -4924,6 +4381,7 @@
 
     private void makeDefault(NetworkAgentInfo newNetwork) {
         if (VDBG) log("Switching to new default network: " + newNetwork);
+        mActiveDefaultNetwork = newNetwork.networkInfo.getType();
         setupDataActivityTracking(newNetwork);
         try {
             mNetd.setDefaultNetId(newNetwork.network.netId);