1 // Copyright 2020 The BoringSSL Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include <openssl/base.h>
16
17 #include <errno.h>
18 #include <limits.h>
19 #include <stdio.h>
20
21 #include <algorithm>
22
23 #include "internal.h"
24
25 #if defined(OPENSSL_WINDOWS)
26 #include <io.h>
27 #else
28 #include <fcntl.h>
29 #include <unistd.h>
30 #endif
31
32
OpenFD(const char * path,int flags)33 ScopedFD OpenFD(const char *path, int flags) {
34 #if defined(OPENSSL_WINDOWS)
35 return ScopedFD(_open(path, flags));
36 #else
37 int fd;
38 do {
39 fd = open(path, flags);
40 } while (fd == -1 && errno == EINTR);
41 return ScopedFD(fd);
42 #endif
43 }
44
CloseFD(int fd)45 void CloseFD(int fd) {
46 #if defined(OPENSSL_WINDOWS)
47 _close(fd);
48 #else
49 close(fd);
50 #endif
51 }
52
ReadFromFD(int fd,size_t * out_bytes_read,void * out,size_t num)53 bool ReadFromFD(int fd, size_t *out_bytes_read, void *out, size_t num) {
54 #if defined(OPENSSL_WINDOWS)
55 // On Windows, the buffer must be at most |INT_MAX|. See
56 // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/read?view=vs-2019
57 int ret = _read(fd, out, std::min(size_t{INT_MAX}, num));
58 #else
59 ssize_t ret;
60 do {
61 ret = read(fd, out, num);
62 } while (ret == -1 && errno == EINVAL);
63 #endif
64
65 if (ret < 0) {
66 *out_bytes_read = 0;
67 return false;
68 }
69 *out_bytes_read = ret;
70 return true;
71 }
72
WriteToFD(int fd,size_t * out_bytes_written,const void * in,size_t num)73 bool WriteToFD(int fd, size_t *out_bytes_written, const void *in, size_t num) {
74 #if defined(OPENSSL_WINDOWS)
75 // The documentation for |_write| does not say the buffer must be at most
76 // |INT_MAX|, but clamp it to |INT_MAX| instead of |UINT_MAX| in case.
77 int ret = _write(fd, in, std::min(size_t{INT_MAX}, num));
78 #else
79 ssize_t ret;
80 do {
81 ret = write(fd, in, num);
82 } while (ret == -1 && errno == EINVAL);
83 #endif
84
85 if (ret < 0) {
86 *out_bytes_written = 0;
87 return false;
88 }
89 *out_bytes_written = ret;
90 return true;
91 }
92
FDToFILE(ScopedFD fd,const char * mode)93 ScopedFILE FDToFILE(ScopedFD fd, const char *mode) {
94 ScopedFILE ret;
95 #if defined(OPENSSL_WINDOWS)
96 ret.reset(_fdopen(fd.get(), mode));
97 #else
98 ret.reset(fdopen(fd.get(), mode));
99 #endif
100 // |fdopen| takes ownership of |fd| on success.
101 if (ret) {
102 fd.release();
103 }
104 return ret;
105 }
106