blob: 9845bc7dd6747c0b676200073ca820dac67dd824 [file] [log] [blame]
Tomasz Wasilczyk87329672019-07-12 11:43:00 -07001/*
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 "NetlinkRequest.h"
18
19#include <android-base/logging.h>
20
21namespace android {
22namespace netdevice {
23namespace impl {
24
25static struct rtattr* nlmsg_tail(struct nlmsghdr* n) {
26 return reinterpret_cast<struct rtattr*>( //
27 reinterpret_cast<uintptr_t>(n) + NLMSG_ALIGN(n->nlmsg_len));
28}
29
30struct rtattr* addattr_l(struct nlmsghdr* n, size_t maxLen, rtattrtype_t type, const void* data,
31 size_t dataLen) {
32 size_t newLen = NLMSG_ALIGN(n->nlmsg_len) + RTA_SPACE(dataLen);
33 if (newLen > maxLen) {
34 LOG(ERROR) << "addattr_l failed - exceeded maxLen: " << newLen << " > " << maxLen;
35 return nullptr;
36 }
37
38 auto attr = nlmsg_tail(n);
39 attr->rta_len = RTA_SPACE(dataLen);
40 attr->rta_type = type;
41 if (dataLen > 0) memcpy(RTA_DATA(attr), data, dataLen);
42
43 n->nlmsg_len = newLen;
44 return attr;
45}
46
47struct rtattr* addattr_nest(struct nlmsghdr* n, size_t maxLen, rtattrtype_t type) {
48 return addattr_l(n, maxLen, type, nullptr, 0);
49}
50
51void addattr_nest_end(struct nlmsghdr* n, struct rtattr* nest) {
52 size_t nestLen = reinterpret_cast<uintptr_t>(nlmsg_tail(n)) - reinterpret_cast<uintptr_t>(nest);
53 nest->rta_len = nestLen;
54}
55
56} // namespace impl
57} // namespace netdevice
58} // namespace android