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 <libnl++/MessageMutator.h>
18 
19 namespace android::nl {
20 
MessageMutator(nlmsghdr * buffer,size_t totalLen)21 MessageMutator::MessageMutator(nlmsghdr* buffer, size_t totalLen)
22     : mConstBuffer(buffer, totalLen), mMutableBuffer(buffer) {
23     CHECK(totalLen >= sizeof(nlmsghdr));
24 }
25 
operator ->() const26 nlmsghdr* MessageMutator::operator->() const {
27     return mMutableBuffer;
28 }
29 
30 MessageMutator::operator Buffer<nlmsghdr>() const {
31     return mConstBuffer;
32 }
33 
read(Buffer<nlattr> attr) const34 uint64_t MessageMutator::read(Buffer<nlattr> attr) const {
35     return attr.data<uint64_t>().copyFirst();
36 }
37 
write(Buffer<nlattr> attr,uint64_t val) const38 void MessageMutator::write(Buffer<nlattr> attr, uint64_t val) const {
39     const auto attrData = attr.data<uint64_t>();
40     const auto offset = mConstBuffer.getOffset(attrData);
41     CHECK(offset.has_value()) << "Trying to write attribute that's not a member of this message";
42 
43     const auto writeableBuffer = reinterpret_cast<uint8_t*>(mMutableBuffer) + *offset;
44     const auto attrSize = attrData.getRaw().len();
45 
46     if (attrSize > sizeof(val)) memset(writeableBuffer, 0, attrSize);
47     memcpy(writeableBuffer, &val, std::min(sizeof(val), attrSize));
48 }
49 
50 }  // namespace android::nl
51