1 /*
2 * Copyright (C) 2020 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 <libnetdevice/vlan.h>
18
19 #include "common.h"
20
21 #include <android-base/logging.h>
22 #include <libnl++/MessageFactory.h>
23 #include <libnl++/Socket.h>
24
25 #include <linux/rtnetlink.h>
26
27 namespace android::netdevice::vlan {
28
add(const std::string & eth,const std::string & vlan,uint16_t id)29 bool add(const std::string& eth, const std::string& vlan, uint16_t id) {
30 const auto ethidx = nametoindex(eth);
31 if (ethidx == 0) {
32 LOG(ERROR) << "Ethernet interface " << eth << " doesn't exist";
33 return false;
34 }
35
36 nl::MessageFactory<ifinfomsg> req(RTM_NEWLINK,
37 NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL | NLM_F_ACK);
38 req.add(IFLA_IFNAME, vlan);
39 req.add<uint32_t>(IFLA_LINK, ethidx);
40
41 {
42 auto linkinfo = req.addNested(IFLA_LINKINFO);
43 req.addBuffer(IFLA_INFO_KIND, "vlan");
44
45 {
46 auto linkinfo = req.addNested(IFLA_INFO_DATA);
47 req.add(IFLA_VLAN_ID, id);
48 }
49 }
50
51 nl::Socket sock(NETLINK_ROUTE);
52 return sock.send(req) && sock.receiveAck(req);
53 }
54
55 } // namespace android::netdevice::vlan
56