blob: 5c3232045e0288506100bc98690e354b3ef9b581 [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
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 <binder/RpcAddress.h>
18
19#include <binder/Parcel.h>
20
21#include "Debug.h"
22#include "RpcState.h"
23#include "RpcWireFormat.h"
24
25namespace android {
26
27RpcAddress RpcAddress::zero() {
28 return RpcAddress();
29}
30
31bool RpcAddress::isZero() const {
32 RpcWireAddress ZERO{0};
33 return memcmp(mRawAddr.get(), &ZERO, sizeof(RpcWireAddress)) == 0;
34}
35
36static void ReadRandomBytes(uint8_t* buf, size_t len) {
37 int fd = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
38 if (fd == -1) {
39 ALOGE("%s: cannot read /dev/urandom", __func__);
40 return;
41 }
42
43 size_t n;
44 while ((n = TEMP_FAILURE_RETRY(read(fd, buf, len))) > 0) {
45 len -= n;
46 buf += n;
47 }
48 if (len > 0) {
49 ALOGW("%s: there are %d bytes skipped", __func__, (int)len);
50 }
51 close(fd);
52}
53
54RpcAddress RpcAddress::unique() {
55 RpcAddress ret;
56 ReadRandomBytes((uint8_t*)ret.mRawAddr.get(), sizeof(RpcWireAddress));
57 LOG_RPC_DETAIL("Creating new address: %s", ret.toString().c_str());
58 return ret;
59}
60
61RpcAddress RpcAddress::fromRawEmbedded(const RpcWireAddress* raw) {
62 RpcAddress addr;
63 memcpy(addr.mRawAddr.get(), raw, sizeof(RpcWireAddress));
64 return addr;
65}
66
67const RpcWireAddress& RpcAddress::viewRawEmbedded() const {
68 return *mRawAddr.get();
69}
70
71bool RpcAddress::operator<(const RpcAddress& rhs) const {
72 return std::memcmp(mRawAddr.get(), rhs.mRawAddr.get(), sizeof(RpcWireAddress)) < 0;
73}
74
75std::string RpcAddress::toString() const {
76 return hexString(mRawAddr.get(), sizeof(RpcWireAddress));
77}
78
79status_t RpcAddress::writeToParcel(Parcel* parcel) const {
80 return parcel->write(mRawAddr.get(), sizeof(RpcWireAddress));
81}
82
83status_t RpcAddress::readFromParcel(const Parcel& parcel) {
84 return parcel.read(mRawAddr.get(), sizeof(RpcWireAddress));
85}
86
87RpcAddress::~RpcAddress() {}
88RpcAddress::RpcAddress() : mRawAddr(std::make_shared<RpcWireAddress>()) {}
89
90} // namespace android