blob: 24ce2bb46525768eea0f0572d7a447993cc023ac [file] [log] [blame]
Andrei Homescu7c0b79f2022-06-30 02:00:46 +00001/*
2 * Copyright (C) 2022 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 "OS.h"
18
19#include <android-base/file.h>
Andrei Homescu024727b2022-08-24 23:54:59 +000020#include <binder/RpcTransportRaw.h>
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000021#include <string.h>
22
23using android::base::ErrnoError;
24using android::base::Result;
25
26namespace android {
27
28Result<void> setNonBlocking(android::base::borrowed_fd fd) {
29 int flags = TEMP_FAILURE_RETRY(fcntl(fd.get(), F_GETFL));
30 if (flags == -1) {
31 return ErrnoError() << "Could not get flags for fd";
32 }
33 if (int ret = TEMP_FAILURE_RETRY(fcntl(fd.get(), F_SETFL, flags | O_NONBLOCK)); ret == -1) {
34 return ErrnoError() << "Could not set non-blocking flag for fd";
35 }
36 return {};
37}
38
39status_t getRandomBytes(uint8_t* data, size_t size) {
40 int ret = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
41 if (ret == -1) {
42 return -errno;
43 }
44
45 base::unique_fd fd(ret);
46 if (!base::ReadFully(fd, data, size)) {
47 return -errno;
48 }
49 return OK;
50}
51
Andrei Homescu24ad36e2022-08-04 01:33:33 +000052status_t dupFileDescriptor(int oldFd, int* newFd) {
53 int ret = fcntl(oldFd, F_DUPFD_CLOEXEC, 0);
54 if (ret < 0) {
55 return -errno;
56 }
57
58 *newFd = ret;
59 return OK;
60}
61
Andrei Homescu024727b2022-08-24 23:54:59 +000062std::unique_ptr<RpcTransportCtxFactory> makeDefaultRpcTransportCtxFactory() {
63 return RpcTransportCtxFactoryRaw::make();
64}
65
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000066} // namespace android