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(std::string_view eth,std::string_view vlan,uint16_t id)29 bool add(std::string_view eth, std::string_view 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, nl::kCreateFlags);
37 req.add(IFLA_IFNAME, vlan);
38 req.add<uint32_t>(IFLA_LINK, ethidx);
39
40 {
41 auto linkinfo = req.addNested(IFLA_LINKINFO);
42 req.addBuffer(IFLA_INFO_KIND, "vlan");
43
44 {
45 auto linkinfo = req.addNested(IFLA_INFO_DATA);
46 req.add(IFLA_VLAN_ID, id);
47 }
48 }
49
50 nl::Socket sock(NETLINK_ROUTE);
51 return sock.send(req) && sock.receiveAck(req);
52 }
53
54 } // namespace android::netdevice::vlan
55