1 /*
2 * Copyright (C) 2019 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/can.h>
18
19 #include "common.h"
20
21 #include <android-base/logging.h>
22 #include <android-base/unique_fd.h>
23 #include <libnl++/MessageFactory.h>
24 #include <libnl++/Socket.h>
25
26 #include <linux/can.h>
27 #include <linux/can/error.h>
28 #include <linux/can/netlink.h>
29 #include <linux/can/raw.h>
30 #include <linux/rtnetlink.h>
31
32 namespace android::netdevice::can {
33
34 static constexpr can_err_mask_t kErrMask = CAN_ERR_MASK;
35
socket(const std::string & ifname)36 base::unique_fd socket(const std::string& ifname) {
37 sockaddr_can addr = {};
38 addr.can_family = AF_CAN;
39 addr.can_ifindex = nametoindex(ifname);
40 if (addr.can_ifindex == 0) {
41 LOG(ERROR) << "Interface " << ifname << " doesn't exists";
42 return {};
43 }
44
45 base::unique_fd sock(::socket(PF_CAN, SOCK_RAW, CAN_RAW));
46 if (!sock.ok()) {
47 LOG(ERROR) << "Failed to create CAN socket";
48 return {};
49 }
50
51 if (setsockopt(sock.get(), SOL_CAN_RAW, CAN_RAW_ERR_FILTER, &kErrMask, sizeof(kErrMask)) < 0) {
52 PLOG(ERROR) << "Can't receive error frames, CAN setsockpt failed";
53 return {};
54 }
55
56 if (0 != fcntl(sock.get(), F_SETFL, O_RDWR | O_NONBLOCK)) {
57 LOG(ERROR) << "Couldn't put CAN socket in non-blocking mode";
58 return {};
59 }
60
61 if (0 != bind(sock.get(), reinterpret_cast<sockaddr*>(&addr), sizeof(addr))) {
62 LOG(ERROR) << "Can't bind to CAN interface " << ifname;
63 return {};
64 }
65
66 return sock;
67 }
68
setBitrate(std::string ifname,uint32_t bitrate)69 bool setBitrate(std::string ifname, uint32_t bitrate) {
70 can_bittiming bt = {};
71 bt.bitrate = bitrate;
72
73 nl::MessageFactory<ifinfomsg> req(RTM_NEWLINK, NLM_F_REQUEST | NLM_F_ACK);
74
75 req->ifi_index = nametoindex(ifname);
76 if (req->ifi_index == 0) {
77 LOG(ERROR) << "Can't find interface " << ifname;
78 return false;
79 }
80
81 {
82 auto linkinfo = req.addNested(IFLA_LINKINFO);
83 req.addBuffer(IFLA_INFO_KIND, "can");
84 {
85 auto infodata = req.addNested(IFLA_INFO_DATA);
86 /* For CAN FD, it would require to add IFLA_CAN_DATA_BITTIMING
87 * and IFLA_CAN_CTRLMODE as well. */
88 req.add(IFLA_CAN_BITTIMING, bt);
89 }
90 }
91
92 nl::Socket sock(NETLINK_ROUTE);
93 return sock.send(req) && sock.receiveAck(req);
94 }
95
96 } // namespace android::netdevice::can
97