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