blob: cc4a03ba67de0b4be135137bd2328ccba902922d [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>
20#include <string.h>
21
22using android::base::ErrnoError;
23using android::base::Result;
24
25namespace android {
26
27Result<void> setNonBlocking(android::base::borrowed_fd fd) {
28 int flags = TEMP_FAILURE_RETRY(fcntl(fd.get(), F_GETFL));
29 if (flags == -1) {
30 return ErrnoError() << "Could not get flags for fd";
31 }
32 if (int ret = TEMP_FAILURE_RETRY(fcntl(fd.get(), F_SETFL, flags | O_NONBLOCK)); ret == -1) {
33 return ErrnoError() << "Could not set non-blocking flag for fd";
34 }
35 return {};
36}
37
38status_t getRandomBytes(uint8_t* data, size_t size) {
39 int ret = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
40 if (ret == -1) {
41 return -errno;
42 }
43
44 base::unique_fd fd(ret);
45 if (!base::ReadFully(fd, data, size)) {
46 return -errno;
47 }
48 return OK;
49}
50
Andrei Homescu24ad36e2022-08-04 01:33:33 +000051status_t dupFileDescriptor(int oldFd, int* newFd) {
52 int ret = fcntl(oldFd, F_DUPFD_CLOEXEC, 0);
53 if (ret < 0) {
54 return -errno;
55 }
56
57 *newFd = ret;
58 return OK;
59}
60
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000061} // namespace android