| 46 | namespace route { |
| 47 | |
| 48 | Try<vector<Rule>> table() |
| 49 | { |
| 50 | Try<Netlink<struct nl_sock>> socket = routing::socket(); |
| 51 | if (socket.isError()) { |
| 52 | return Error(socket.error()); |
| 53 | } |
| 54 | |
| 55 | // Dump all the routes (for IPv4) from kernel. |
| 56 | struct nl_cache* c = nullptr; |
| 57 | int error = rtnl_route_alloc_cache(socket->get(), AF_INET, 0, &c); |
| 58 | if (error != 0) { |
| 59 | return Error(nl_geterror(error)); |
| 60 | } |
| 61 | |
| 62 | Netlink<struct nl_cache> cache(c); |
| 63 | |
| 64 | vector<Rule> results; |
| 65 | |
| 66 | // Scan the routes and look for entries in the main routing table. |
| 67 | for (struct nl_object* o = nl_cache_get_first(cache.get()); |
| 68 | o != nullptr; o = nl_cache_get_next(o)) { |
| 69 | struct rtnl_route* route = (struct rtnl_route*) o; |
| 70 | |
| 71 | // TODO(jieyu): Currently, we assume each route in the routing |
| 72 | // table has only one hop (which is true in most environments). |
| 73 | if (rtnl_route_get_table(route) == RT_TABLE_MAIN && |
| 74 | rtnl_route_get_nnexthops(route) == 1) { |
| 75 | CHECK_EQ(AF_INET, rtnl_route_get_family(route)); |
| 76 | |
| 77 | // Get the destination IP network if exists. |
| 78 | Option<net::IP::Network> destination; |
| 79 | struct nl_addr* dst = rtnl_route_get_dst(route); |
| 80 | if (dst != nullptr && nl_addr_get_len(dst) != 0) { |
| 81 | struct in_addr* addr = (struct in_addr*) nl_addr_get_binary_addr(dst); |
| 82 | Try<net::IP::Network> network = net::IP::Network::create( |
| 83 | net::IP(*addr), |
| 84 | nl_addr_get_prefixlen(dst)); |
| 85 | |
| 86 | if (network.isError()) { |
| 87 | return Error( |
| 88 | "Invalid IP network format from the routing table: " + |
| 89 | network.error()); |
| 90 | } |
| 91 | |
| 92 | destination = network.get(); |
| 93 | } |
| 94 | |
| 95 | // Get the default gateway if exists. |
| 96 | Option<net::IP> gateway; |
| 97 | struct rtnl_nexthop* hop = rtnl_route_nexthop_n(route, 0); |
| 98 | struct nl_addr* gw = rtnl_route_nh_get_gateway(CHECK_NOTNULL(hop)); |
| 99 | if (gw != nullptr && nl_addr_get_len(gw) != 0) { |
| 100 | struct in_addr* addr = (struct in_addr*) nl_addr_get_binary_addr(gw); |
| 101 | gateway = net::IP(*addr); |
| 102 | } |
| 103 | |
| 104 | // Get the destination link. |
| 105 | int index = rtnl_route_nh_get_ifindex(hop); |