• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <libnl++/MessageFactory.h>
18 
19 #include <android-base/logging.h>
20 #include <libnl++/bits.h>
21 
22 namespace android::nl {
23 
tail(nlmsghdr * msg)24 static nlattr* tail(nlmsghdr* msg) {
25     return reinterpret_cast<nlattr*>(uintptr_t(msg) + impl::align(msg->nlmsg_len));
26 }
27 
add(nlmsghdr * msg,size_t maxLen,nlattrtype_t type,const void * data,size_t dataLen)28 nlattr* MessageFactoryBase::add(nlmsghdr* msg, size_t maxLen, nlattrtype_t type, const void* data,
29                                 size_t dataLen) {
30     const auto totalAttrLen = impl::length<nlattr>(dataLen);
31     const auto newLen = impl::align(msg->nlmsg_len) + impl::align(totalAttrLen);
32     if (newLen > maxLen) {
33         LOG(ERROR) << "Can't add attribute of size " << dataLen  //
34                    << " - exceeded maxLen: " << newLen << " > " << maxLen;
35         return nullptr;
36     }
37 
38     auto attr = tail(msg);
39     attr->nla_len = totalAttrLen;
40     attr->nla_type = type;
41     if (dataLen > 0) memcpy(impl::data<nlattr, void>(attr), data, dataLen);
42 
43     msg->nlmsg_len = newLen;
44     return attr;
45 }
46 
closeNested(nlmsghdr * msg,nlattr * nested)47 void MessageFactoryBase::closeNested(nlmsghdr* msg, nlattr* nested) {
48     if (nested == nullptr) return;
49     nested->nla_len = uintptr_t(tail(msg)) - uintptr_t(nested);
50 }
51 
52 }  // namespace android::nl
53