Home | History | Annotate | Download | only in server
      1 /*
      2  * Copyright (C) 2014 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 // THREAD-SAFETY
     18 // -------------
     19 // The methods in this file are called from multiple threads (from CommandListener, FwmarkServer
     20 // and DnsProxyListener). So, all accesses to shared state are guarded by a lock.
     21 //
     22 // In some cases, a single non-const method acquires and releases the lock several times, like so:
     23 //     if (isValidNetwork(...)) {  // isValidNetwork() acquires and releases the lock.
     24 //        setDefaultNetwork(...);  // setDefaultNetwork() also acquires and releases the lock.
     25 //
     26 // It might seem that this allows races where the state changes between the two statements, but in
     27 // fact there are no races because:
     28 //     1. This pattern only occurs in non-const methods (i.e., those that mutate state).
     29 //     2. Only CommandListener calls these non-const methods. The others call only const methods.
     30 //     3. CommandListener only processes one command at a time. I.e., it's serialized.
     31 // Thus, no other mutation can occur in between the two statements above.
     32 
     33 #include "NetworkController.h"
     34 
     35 #define LOG_TAG "Netd"
     36 #include "log/log.h"
     37 
     38 #include "cutils/misc.h"
     39 #include "resolv_netid.h"
     40 
     41 #include "Controllers.h"
     42 #include "DummyNetwork.h"
     43 #include "DumpWriter.h"
     44 #include "Fwmark.h"
     45 #include "LocalNetwork.h"
     46 #include "PhysicalNetwork.h"
     47 #include "RouteController.h"
     48 #include "VirtualNetwork.h"
     49 
     50 #define DBG 0
     51 
     52 namespace android {
     53 namespace net {
     54 
     55 namespace {
     56 
     57 // Keep these in sync with ConnectivityService.java.
     58 const unsigned MIN_NET_ID = 100;
     59 const unsigned MAX_NET_ID = 65535;
     60 
     61 }  // namespace
     62 
     63 const unsigned NetworkController::MIN_OEM_ID   =  1;
     64 const unsigned NetworkController::MAX_OEM_ID   = 50;
     65 const unsigned NetworkController::DUMMY_NET_ID = 51;
     66 // NetIds 52..98 are reserved for future use.
     67 const unsigned NetworkController::LOCAL_NET_ID = 99;
     68 
     69 // All calls to methods here are made while holding a write lock on mRWLock.
     70 class NetworkController::DelegateImpl : public PhysicalNetwork::Delegate {
     71 public:
     72     explicit DelegateImpl(NetworkController* networkController);
     73     virtual ~DelegateImpl();
     74 
     75     int modifyFallthrough(unsigned vpnNetId, const std::string& physicalInterface,
     76                           Permission permission, bool add) WARN_UNUSED_RESULT;
     77 
     78 private:
     79     int addFallthrough(const std::string& physicalInterface,
     80                        Permission permission) override WARN_UNUSED_RESULT;
     81     int removeFallthrough(const std::string& physicalInterface,
     82                           Permission permission) override WARN_UNUSED_RESULT;
     83 
     84     int modifyFallthrough(const std::string& physicalInterface, Permission permission,
     85                           bool add) WARN_UNUSED_RESULT;
     86 
     87     NetworkController* const mNetworkController;
     88 };
     89 
     90 NetworkController::DelegateImpl::DelegateImpl(NetworkController* networkController) :
     91         mNetworkController(networkController) {
     92 }
     93 
     94 NetworkController::DelegateImpl::~DelegateImpl() {
     95 }
     96 
     97 int NetworkController::DelegateImpl::modifyFallthrough(unsigned vpnNetId,
     98                                                        const std::string& physicalInterface,
     99                                                        Permission permission, bool add) {
    100     if (add) {
    101         if (int ret = RouteController::addVirtualNetworkFallthrough(vpnNetId,
    102                                                                     physicalInterface.c_str(),
    103                                                                     permission)) {
    104             ALOGE("failed to add fallthrough to %s for VPN netId %u", physicalInterface.c_str(),
    105                   vpnNetId);
    106             return ret;
    107         }
    108     } else {
    109         if (int ret = RouteController::removeVirtualNetworkFallthrough(vpnNetId,
    110                                                                        physicalInterface.c_str(),
    111                                                                        permission)) {
    112             ALOGE("failed to remove fallthrough to %s for VPN netId %u", physicalInterface.c_str(),
    113                   vpnNetId);
    114             return ret;
    115         }
    116     }
    117     return 0;
    118 }
    119 
    120 int NetworkController::DelegateImpl::addFallthrough(const std::string& physicalInterface,
    121                                                     Permission permission) {
    122     return modifyFallthrough(physicalInterface, permission, true);
    123 }
    124 
    125 int NetworkController::DelegateImpl::removeFallthrough(const std::string& physicalInterface,
    126                                                        Permission permission) {
    127     return modifyFallthrough(physicalInterface, permission, false);
    128 }
    129 
    130 int NetworkController::DelegateImpl::modifyFallthrough(const std::string& physicalInterface,
    131                                                        Permission permission, bool add) {
    132     for (const auto& entry : mNetworkController->mNetworks) {
    133         if (entry.second->getType() == Network::VIRTUAL) {
    134             if (int ret = modifyFallthrough(entry.first, physicalInterface, permission, add)) {
    135                 return ret;
    136             }
    137         }
    138     }
    139     return 0;
    140 }
    141 
    142 NetworkController::NetworkController() :
    143         mDelegateImpl(new NetworkController::DelegateImpl(this)), mDefaultNetId(NETID_UNSET),
    144         mProtectableUsers({AID_VPN}) {
    145     mNetworks[LOCAL_NET_ID] = new LocalNetwork(LOCAL_NET_ID);
    146     mNetworks[DUMMY_NET_ID] = new DummyNetwork(DUMMY_NET_ID);
    147 }
    148 
    149 unsigned NetworkController::getDefaultNetwork() const {
    150     android::RWLock::AutoRLock lock(mRWLock);
    151     return mDefaultNetId;
    152 }
    153 
    154 int NetworkController::setDefaultNetwork(unsigned netId) {
    155     android::RWLock::AutoWLock lock(mRWLock);
    156 
    157     if (netId == mDefaultNetId) {
    158         return 0;
    159     }
    160 
    161     if (netId != NETID_UNSET) {
    162         Network* network = getNetworkLocked(netId);
    163         if (!network) {
    164             ALOGE("no such netId %u", netId);
    165             return -ENONET;
    166         }
    167         if (network->getType() != Network::PHYSICAL) {
    168             ALOGE("cannot set default to non-physical network with netId %u", netId);
    169             return -EINVAL;
    170         }
    171         if (int ret = static_cast<PhysicalNetwork*>(network)->addAsDefault()) {
    172             return ret;
    173         }
    174     }
    175 
    176     if (mDefaultNetId != NETID_UNSET) {
    177         Network* network = getNetworkLocked(mDefaultNetId);
    178         if (!network || network->getType() != Network::PHYSICAL) {
    179             ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
    180             return -ESRCH;
    181         }
    182         if (int ret = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
    183             return ret;
    184         }
    185     }
    186 
    187     mDefaultNetId = netId;
    188     return 0;
    189 }
    190 
    191 uint32_t NetworkController::getNetworkForDns(unsigned* netId, uid_t uid) const {
    192     android::RWLock::AutoRLock lock(mRWLock);
    193     Fwmark fwmark;
    194     fwmark.protectedFromVpn = true;
    195     fwmark.permission = PERMISSION_SYSTEM;
    196     if (checkUserNetworkAccessLocked(uid, *netId) == 0) {
    197         // If a non-zero NetId was explicitly specified, and the user has permission for that
    198         // network, use that network's DNS servers. Do not fall through to the default network even
    199         // if the explicitly selected network is a split tunnel VPN: the explicitlySelected bit
    200         // ensures that the VPN fallthrough rule does not match.
    201         fwmark.explicitlySelected = true;
    202 
    203         // If the network is a VPN and it doesn't have DNS servers, use the default network's DNS
    204         // servers (through the default network). Otherwise, the query is guaranteed to fail.
    205         // http://b/29498052
    206         Network *network = getNetworkLocked(*netId);
    207         if (network && network->getType() == Network::VIRTUAL &&
    208                 !static_cast<VirtualNetwork *>(network)->getHasDns()) {
    209             *netId = mDefaultNetId;
    210         }
    211     } else {
    212         // If the user is subject to a VPN and the VPN provides DNS servers, use those servers
    213         // (possibly falling through to the default network if the VPN doesn't provide a route to
    214         // them). Otherwise, use the default network's DNS servers.
    215         VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
    216         if (virtualNetwork && virtualNetwork->getHasDns()) {
    217             *netId = virtualNetwork->getNetId();
    218         } else {
    219             // TODO: return an error instead of silently doing the DNS lookup on the wrong network.
    220             // http://b/27560555
    221             *netId = mDefaultNetId;
    222         }
    223     }
    224     fwmark.netId = *netId;
    225     return fwmark.intValue;
    226 }
    227 
    228 // Returns the NetId that a given UID would use if no network is explicitly selected. Specifically,
    229 // the VPN that applies to the UID if any; otherwise, the default network.
    230 unsigned NetworkController::getNetworkForUser(uid_t uid) const {
    231     android::RWLock::AutoRLock lock(mRWLock);
    232     if (VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid)) {
    233         return virtualNetwork->getNetId();
    234     }
    235     return mDefaultNetId;
    236 }
    237 
    238 // Returns the NetId that will be set when a socket connect()s. This is the bypassable VPN that
    239 // applies to the user if any; otherwise, the default network.
    240 //
    241 // In general, we prefer to always set the default network's NetId in connect(), so that if the VPN
    242 // is a split-tunnel and disappears later, the socket continues working (since the default network's
    243 // NetId is still valid). Secure VPNs will correctly grab the socket's traffic since they have a
    244 // high-priority routing rule that doesn't care what NetId the socket has.
    245 //
    246 // But bypassable VPNs have a very low priority rule, so we need to mark the socket with the
    247 // bypassable VPN's NetId if we expect it to get any traffic at all. If the bypassable VPN is a
    248 // split-tunnel, that's okay, because we have fallthrough rules that will direct the fallthrough
    249 // traffic to the default network. But it does mean that if the bypassable VPN goes away (and thus
    250 // the fallthrough rules also go away), the socket that used to fallthrough to the default network
    251 // will stop working.
    252 unsigned NetworkController::getNetworkForConnect(uid_t uid) const {
    253     android::RWLock::AutoRLock lock(mRWLock);
    254     VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
    255     if (virtualNetwork && !virtualNetwork->isSecure()) {
    256         return virtualNetwork->getNetId();
    257     }
    258     return mDefaultNetId;
    259 }
    260 
    261 void NetworkController::getNetworkContext(
    262         unsigned netId, uid_t uid, struct android_net_context* netcontext) const {
    263     struct android_net_context nc = {
    264             .app_netid = netId,
    265             .app_mark = MARK_UNSET,
    266             .dns_netid = netId,
    267             .dns_mark = MARK_UNSET,
    268             .uid = uid,
    269     };
    270 
    271     // |netId| comes directly (via dnsproxyd) from the value returned by netIdForResolv() in the
    272     // client process. This value is nonzero iff.:
    273     //
    274     // 1. The app specified a netid/nethandle to a DNS resolution method such as:
    275     //        - [Java] android.net.Network#getAllByName()
    276     //        - [C/++] android_getaddrinfofornetwork()
    277     // 2. The app specified a netid/nethandle to be used as a process default via:
    278     //        - [Java] android.net.ConnectivityManager#bindProcessToNetwork()
    279     //        - [C/++] android_setprocnetwork()
    280     // 3. The app called android.net.ConnectivityManager#startUsingNetworkFeature().
    281     //
    282     // In all these cases (with the possible exception of #3), the right thing to do is to treat
    283     // such cases as explicitlySelected.
    284     const bool explicitlySelected = (nc.app_netid != NETID_UNSET);
    285     if (!explicitlySelected) {
    286         nc.app_netid = getNetworkForConnect(uid);
    287     }
    288 
    289     Fwmark fwmark;
    290     fwmark.netId = nc.app_netid;
    291     fwmark.explicitlySelected = explicitlySelected;
    292     fwmark.protectedFromVpn = explicitlySelected && canProtect(uid);
    293     fwmark.permission = getPermissionForUser(uid);
    294     nc.app_mark = fwmark.intValue;
    295 
    296     nc.dns_mark = getNetworkForDns(&(nc.dns_netid), uid);
    297 
    298     if (DBG) {
    299         ALOGD("app_netid:0x%x app_mark:0x%x dns_netid:0x%x dns_mark:0x%x uid:%d",
    300               nc.app_netid, nc.app_mark, nc.dns_netid, nc.dns_mark, uid);
    301     }
    302 
    303     if (netcontext) {
    304         *netcontext = nc;
    305     }
    306 }
    307 
    308 unsigned NetworkController::getNetworkForInterface(const char* interface) const {
    309     android::RWLock::AutoRLock lock(mRWLock);
    310     for (const auto& entry : mNetworks) {
    311         if (entry.second->hasInterface(interface)) {
    312             return entry.first;
    313         }
    314     }
    315     return NETID_UNSET;
    316 }
    317 
    318 bool NetworkController::isVirtualNetwork(unsigned netId) const {
    319     android::RWLock::AutoRLock lock(mRWLock);
    320     Network* network = getNetworkLocked(netId);
    321     return network && network->getType() == Network::VIRTUAL;
    322 }
    323 
    324 int NetworkController::createPhysicalNetworkLocked(unsigned netId, Permission permission) {
    325     if (!((MIN_NET_ID <= netId && netId <= MAX_NET_ID) ||
    326           (MIN_OEM_ID <= netId && netId <= MAX_OEM_ID))) {
    327         ALOGE("invalid netId %u", netId);
    328         return -EINVAL;
    329     }
    330 
    331     if (isValidNetworkLocked(netId)) {
    332         ALOGE("duplicate netId %u", netId);
    333         return -EEXIST;
    334     }
    335 
    336     PhysicalNetwork* physicalNetwork = new PhysicalNetwork(netId, mDelegateImpl);
    337     if (int ret = physicalNetwork->setPermission(permission)) {
    338         ALOGE("inconceivable! setPermission cannot fail on an empty network");
    339         delete physicalNetwork;
    340         return ret;
    341     }
    342 
    343     mNetworks[netId] = physicalNetwork;
    344     return 0;
    345 }
    346 
    347 int NetworkController::createPhysicalNetwork(unsigned netId, Permission permission) {
    348     android::RWLock::AutoWLock lock(mRWLock);
    349     return createPhysicalNetworkLocked(netId, permission);
    350 }
    351 
    352 int NetworkController::createPhysicalOemNetwork(Permission permission, unsigned *pNetId) {
    353     if (pNetId == NULL) {
    354         return -EINVAL;
    355     }
    356 
    357     android::RWLock::AutoWLock lock(mRWLock);
    358     for (*pNetId = MIN_OEM_ID; *pNetId <= MAX_OEM_ID; (*pNetId)++) {
    359         if (!isValidNetworkLocked(*pNetId)) {
    360             break;
    361         }
    362     }
    363 
    364     if (*pNetId > MAX_OEM_ID) {
    365         ALOGE("No free network ID");
    366         *pNetId = 0;
    367         return -ENONET;
    368     }
    369 
    370     int ret = createPhysicalNetworkLocked(*pNetId, permission);
    371     if (ret) {
    372         *pNetId = 0;
    373     }
    374 
    375     return ret;
    376 }
    377 
    378 int NetworkController::createVirtualNetwork(unsigned netId, bool hasDns, bool secure) {
    379     if (!(MIN_NET_ID <= netId && netId <= MAX_NET_ID)) {
    380         ALOGE("invalid netId %u", netId);
    381         return -EINVAL;
    382     }
    383 
    384     if (isValidNetwork(netId)) {
    385         ALOGE("duplicate netId %u", netId);
    386         return -EEXIST;
    387     }
    388 
    389     android::RWLock::AutoWLock lock(mRWLock);
    390     if (int ret = modifyFallthroughLocked(netId, true)) {
    391         return ret;
    392     }
    393     mNetworks[netId] = new VirtualNetwork(netId, hasDns, secure);
    394     return 0;
    395 }
    396 
    397 int NetworkController::destroyNetwork(unsigned netId) {
    398     if (netId == LOCAL_NET_ID) {
    399         ALOGE("cannot destroy local network");
    400         return -EINVAL;
    401     }
    402     if (!isValidNetwork(netId)) {
    403         ALOGE("no such netId %u", netId);
    404         return -ENONET;
    405     }
    406 
    407     // TODO: ioctl(SIOCKILLADDR, ...) to kill all sockets on the old network.
    408 
    409     android::RWLock::AutoWLock lock(mRWLock);
    410     Network* network = getNetworkLocked(netId);
    411 
    412     // If we fail to destroy a network, things will get stuck badly. Therefore, unlike most of the
    413     // other network code, ignore failures and attempt to clear out as much state as possible, even
    414     // if we hit an error on the way. Return the first error that we see.
    415     int ret = network->clearInterfaces();
    416 
    417     if (mDefaultNetId == netId) {
    418         if (int err = static_cast<PhysicalNetwork*>(network)->removeAsDefault()) {
    419             ALOGE("inconceivable! removeAsDefault cannot fail on an empty network");
    420             if (!ret) {
    421                 ret = err;
    422             }
    423         }
    424         mDefaultNetId = NETID_UNSET;
    425     } else if (network->getType() == Network::VIRTUAL) {
    426         if (int err = modifyFallthroughLocked(netId, false)) {
    427             if (!ret) {
    428                 ret = err;
    429             }
    430         }
    431     }
    432     mNetworks.erase(netId);
    433     delete network;
    434     _resolv_delete_cache_for_net(netId);
    435     return ret;
    436 }
    437 
    438 int NetworkController::addInterfaceToNetwork(unsigned netId, const char* interface) {
    439     if (!isValidNetwork(netId)) {
    440         ALOGE("no such netId %u", netId);
    441         return -ENONET;
    442     }
    443 
    444     unsigned existingNetId = getNetworkForInterface(interface);
    445     if (existingNetId != NETID_UNSET && existingNetId != netId) {
    446         ALOGE("interface %s already assigned to netId %u", interface, existingNetId);
    447         return -EBUSY;
    448     }
    449 
    450     android::RWLock::AutoWLock lock(mRWLock);
    451     return getNetworkLocked(netId)->addInterface(interface);
    452 }
    453 
    454 int NetworkController::removeInterfaceFromNetwork(unsigned netId, const char* interface) {
    455     if (!isValidNetwork(netId)) {
    456         ALOGE("no such netId %u", netId);
    457         return -ENONET;
    458     }
    459 
    460     android::RWLock::AutoWLock lock(mRWLock);
    461     return getNetworkLocked(netId)->removeInterface(interface);
    462 }
    463 
    464 Permission NetworkController::getPermissionForUser(uid_t uid) const {
    465     android::RWLock::AutoRLock lock(mRWLock);
    466     return getPermissionForUserLocked(uid);
    467 }
    468 
    469 void NetworkController::setPermissionForUsers(Permission permission,
    470                                               const std::vector<uid_t>& uids) {
    471     android::RWLock::AutoWLock lock(mRWLock);
    472     for (uid_t uid : uids) {
    473         mUsers[uid] = permission;
    474     }
    475 }
    476 
    477 int NetworkController::checkUserNetworkAccess(uid_t uid, unsigned netId) const {
    478     android::RWLock::AutoRLock lock(mRWLock);
    479     return checkUserNetworkAccessLocked(uid, netId);
    480 }
    481 
    482 int NetworkController::setPermissionForNetworks(Permission permission,
    483                                                 const std::vector<unsigned>& netIds) {
    484     android::RWLock::AutoWLock lock(mRWLock);
    485     for (unsigned netId : netIds) {
    486         Network* network = getNetworkLocked(netId);
    487         if (!network) {
    488             ALOGE("no such netId %u", netId);
    489             return -ENONET;
    490         }
    491         if (network->getType() != Network::PHYSICAL) {
    492             ALOGE("cannot set permissions on non-physical network with netId %u", netId);
    493             return -EINVAL;
    494         }
    495 
    496         if (int ret = static_cast<PhysicalNetwork*>(network)->setPermission(permission)) {
    497             return ret;
    498         }
    499     }
    500     return 0;
    501 }
    502 
    503 int NetworkController::addUsersToNetwork(unsigned netId, const UidRanges& uidRanges) {
    504     android::RWLock::AutoWLock lock(mRWLock);
    505     Network* network = getNetworkLocked(netId);
    506     if (!network) {
    507         ALOGE("no such netId %u", netId);
    508         return -ENONET;
    509     }
    510     if (network->getType() != Network::VIRTUAL) {
    511         ALOGE("cannot add users to non-virtual network with netId %u", netId);
    512         return -EINVAL;
    513     }
    514     if (int ret = static_cast<VirtualNetwork*>(network)->addUsers(uidRanges, mProtectableUsers)) {
    515         return ret;
    516     }
    517     return 0;
    518 }
    519 
    520 int NetworkController::removeUsersFromNetwork(unsigned netId, const UidRanges& uidRanges) {
    521     android::RWLock::AutoWLock lock(mRWLock);
    522     Network* network = getNetworkLocked(netId);
    523     if (!network) {
    524         ALOGE("no such netId %u", netId);
    525         return -ENONET;
    526     }
    527     if (network->getType() != Network::VIRTUAL) {
    528         ALOGE("cannot remove users from non-virtual network with netId %u", netId);
    529         return -EINVAL;
    530     }
    531     if (int ret = static_cast<VirtualNetwork*>(network)->removeUsers(uidRanges,
    532                                                                      mProtectableUsers)) {
    533         return ret;
    534     }
    535     return 0;
    536 }
    537 
    538 int NetworkController::addRoute(unsigned netId, const char* interface, const char* destination,
    539                                 const char* nexthop, bool legacy, uid_t uid) {
    540     return modifyRoute(netId, interface, destination, nexthop, true, legacy, uid);
    541 }
    542 
    543 int NetworkController::removeRoute(unsigned netId, const char* interface, const char* destination,
    544                                    const char* nexthop, bool legacy, uid_t uid) {
    545     return modifyRoute(netId, interface, destination, nexthop, false, legacy, uid);
    546 }
    547 
    548 bool NetworkController::canProtect(uid_t uid) const {
    549     android::RWLock::AutoRLock lock(mRWLock);
    550     return ((getPermissionForUserLocked(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) ||
    551            mProtectableUsers.find(uid) != mProtectableUsers.end();
    552 }
    553 
    554 void NetworkController::allowProtect(const std::vector<uid_t>& uids) {
    555     android::RWLock::AutoWLock lock(mRWLock);
    556     mProtectableUsers.insert(uids.begin(), uids.end());
    557 }
    558 
    559 void NetworkController::denyProtect(const std::vector<uid_t>& uids) {
    560     android::RWLock::AutoWLock lock(mRWLock);
    561     for (uid_t uid : uids) {
    562         mProtectableUsers.erase(uid);
    563     }
    564 }
    565 
    566 void NetworkController::dump(DumpWriter& dw) {
    567     android::RWLock::AutoRLock lock(mRWLock);
    568 
    569     dw.incIndent();
    570     dw.println("NetworkController");
    571 
    572     dw.incIndent();
    573     dw.println("Default network: %u", mDefaultNetId);
    574 
    575     dw.blankline();
    576     dw.println("Networks:");
    577     dw.incIndent();
    578     for (const auto& i : mNetworks) {
    579         Network* network = i.second;
    580         dw.println(network->toString().c_str());
    581         if (network->getType() == Network::PHYSICAL) {
    582             dw.incIndent();
    583             Permission permission = reinterpret_cast<PhysicalNetwork*>(network)->getPermission();
    584             dw.println("Required permission: %s", permissionToName(permission));
    585             dw.decIndent();
    586         }
    587         android::net::gCtls->resolverCtrl.dump(dw, i.first);
    588         dw.blankline();
    589     }
    590     dw.decIndent();
    591 
    592     dw.decIndent();
    593 
    594     dw.decIndent();
    595 }
    596 
    597 bool NetworkController::isValidNetworkLocked(unsigned netId) const {
    598     return getNetworkLocked(netId);
    599 }
    600 
    601 bool NetworkController::isValidNetwork(unsigned netId) const {
    602     android::RWLock::AutoRLock lock(mRWLock);
    603     return isValidNetworkLocked(netId);
    604 }
    605 
    606 Network* NetworkController::getNetworkLocked(unsigned netId) const {
    607     auto iter = mNetworks.find(netId);
    608     return iter == mNetworks.end() ? NULL : iter->second;
    609 }
    610 
    611 VirtualNetwork* NetworkController::getVirtualNetworkForUserLocked(uid_t uid) const {
    612     for (const auto& entry : mNetworks) {
    613         if (entry.second->getType() == Network::VIRTUAL) {
    614             VirtualNetwork* virtualNetwork = static_cast<VirtualNetwork*>(entry.second);
    615             if (virtualNetwork->appliesToUser(uid)) {
    616                 return virtualNetwork;
    617             }
    618         }
    619     }
    620     return NULL;
    621 }
    622 
    623 Permission NetworkController::getPermissionForUserLocked(uid_t uid) const {
    624     auto iter = mUsers.find(uid);
    625     if (iter != mUsers.end()) {
    626         return iter->second;
    627     }
    628     return uid < FIRST_APPLICATION_UID ? PERMISSION_SYSTEM : PERMISSION_NONE;
    629 }
    630 
    631 int NetworkController::checkUserNetworkAccessLocked(uid_t uid, unsigned netId) const {
    632     Network* network = getNetworkLocked(netId);
    633     if (!network) {
    634         return -ENONET;
    635     }
    636 
    637     // If uid is INVALID_UID, this likely means that we were unable to retrieve the UID of the peer
    638     // (using SO_PEERCRED). Be safe and deny access to the network, even if it's valid.
    639     if (uid == INVALID_UID) {
    640         return -EREMOTEIO;
    641     }
    642     Permission userPermission = getPermissionForUserLocked(uid);
    643     if ((userPermission & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
    644         return 0;
    645     }
    646     if (network->getType() == Network::VIRTUAL) {
    647         return static_cast<VirtualNetwork*>(network)->appliesToUser(uid) ? 0 : -EPERM;
    648     }
    649     VirtualNetwork* virtualNetwork = getVirtualNetworkForUserLocked(uid);
    650     if (virtualNetwork && virtualNetwork->isSecure() &&
    651             mProtectableUsers.find(uid) == mProtectableUsers.end()) {
    652         return -EPERM;
    653     }
    654     Permission networkPermission = static_cast<PhysicalNetwork*>(network)->getPermission();
    655     return ((userPermission & networkPermission) == networkPermission) ? 0 : -EACCES;
    656 }
    657 
    658 int NetworkController::modifyRoute(unsigned netId, const char* interface, const char* destination,
    659                                    const char* nexthop, bool add, bool legacy, uid_t uid) {
    660     if (!isValidNetwork(netId)) {
    661         ALOGE("no such netId %u", netId);
    662         return -ENONET;
    663     }
    664     unsigned existingNetId = getNetworkForInterface(interface);
    665     if (existingNetId == NETID_UNSET) {
    666         ALOGE("interface %s not assigned to any netId", interface);
    667         return -ENODEV;
    668     }
    669     if (existingNetId != netId) {
    670         ALOGE("interface %s assigned to netId %u, not %u", interface, existingNetId, netId);
    671         return -ENOENT;
    672     }
    673 
    674     RouteController::TableType tableType;
    675     if (netId == LOCAL_NET_ID) {
    676         tableType = RouteController::LOCAL_NETWORK;
    677     } else if (legacy) {
    678         if ((getPermissionForUser(uid) & PERMISSION_SYSTEM) == PERMISSION_SYSTEM) {
    679             tableType = RouteController::LEGACY_SYSTEM;
    680         } else {
    681             tableType = RouteController::LEGACY_NETWORK;
    682         }
    683     } else {
    684         tableType = RouteController::INTERFACE;
    685     }
    686 
    687     return add ? RouteController::addRoute(interface, destination, nexthop, tableType) :
    688                  RouteController::removeRoute(interface, destination, nexthop, tableType);
    689 }
    690 
    691 int NetworkController::modifyFallthroughLocked(unsigned vpnNetId, bool add) {
    692     if (mDefaultNetId == NETID_UNSET) {
    693         return 0;
    694     }
    695     Network* network = getNetworkLocked(mDefaultNetId);
    696     if (!network) {
    697         ALOGE("cannot find previously set default network with netId %u", mDefaultNetId);
    698         return -ESRCH;
    699     }
    700     if (network->getType() != Network::PHYSICAL) {
    701         ALOGE("inconceivable! default network must be a physical network");
    702         return -EINVAL;
    703     }
    704     Permission permission = static_cast<PhysicalNetwork*>(network)->getPermission();
    705     for (const auto& physicalInterface : network->getInterfaces()) {
    706         if (int ret = mDelegateImpl->modifyFallthrough(vpnNetId, physicalInterface, permission,
    707                                                        add)) {
    708             return ret;
    709         }
    710     }
    711     return 0;
    712 }
    713 
    714 }  // namespace net
    715 }  // namespace android
    716