• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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 #include "router.h"
18 
19 #include "netlink.h"
20 
21 #include <linux/rtnetlink.h>
22 
23 #include <errno.h>
24 #include <string.h>
25 #include <unistd.h>
26 
Router()27 Router::Router() : mSocketFd(-1) {}
28 
~Router()29 Router::~Router() {
30     if (mSocketFd != -1) {
31         ::close(mSocketFd);
32         mSocketFd = -1;
33     }
34 }
35 
init()36 Result Router::init() {
37     // Create a netlink socket to the router
38     mSocketFd = ::socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
39     if (mSocketFd == -1) {
40         return Result::error(strerror(errno));
41     }
42     return Result::success();
43 }
44 
setDefaultGateway(in_addr_t gateway,unsigned int ifaceIndex)45 Result Router::setDefaultGateway(in_addr_t gateway, unsigned int ifaceIndex) {
46     struct Request {
47         struct nlmsghdr hdr;
48         struct rtmsg msg;
49         char buf[256];
50     } request;
51 
52     memset(&request, 0, sizeof(request));
53 
54     // Set up a request to create a new route
55     request.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(request.msg));
56     request.hdr.nlmsg_type = RTM_NEWROUTE;
57     request.hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE;
58 
59     request.msg.rtm_family = AF_INET;
60     request.msg.rtm_dst_len = 0;
61     request.msg.rtm_table = RT_TABLE_MAIN;
62     request.msg.rtm_protocol = RTPROT_BOOT;
63     request.msg.rtm_scope = RT_SCOPE_UNIVERSE;
64     request.msg.rtm_type = RTN_UNICAST;
65 
66     addRouterAttribute(request, RTA_GATEWAY, &gateway, sizeof(gateway));
67     addRouterAttribute(request, RTA_OIF, &ifaceIndex, sizeof(ifaceIndex));
68 
69     return sendNetlinkMessage(&request, request.hdr.nlmsg_len);
70 }
71 
sendNetlinkMessage(const void * data,size_t size)72 Result Router::sendNetlinkMessage(const void* data, size_t size) {
73     struct sockaddr_nl nlAddress;
74     memset(&nlAddress, 0, sizeof(nlAddress));
75     nlAddress.nl_family = AF_NETLINK;
76 
77     int res = ::sendto(mSocketFd, data, size, 0, reinterpret_cast<sockaddr*>(&nlAddress),
78                        sizeof(nlAddress));
79     if (res == -1) {
80         return Result::error("Unable to send on netlink socket: %s", strerror(errno));
81     }
82     return Result::success();
83 }
84