xref: /aosp_15_r20/external/conscrypt/common/src/jni/main/cpp/conscrypt/netutil.cc (revision cd0cc2e34ba52cdf454361820a14d744e4bd531d)
1 /*
2  * Copyright (C) 2017 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 <conscrypt/netutil.h>
18 #include <conscrypt/trace.h>
19 
20 #ifdef _WIN32
21 #pragma comment(lib, "ws2_32.lib")
22 #include <winsock2.h>
23 #else  // !_WIN32
24 #include <arpa/inet.h>
25 #include <fcntl.h>
26 #include <poll.h>
27 #include <sys/socket.h>
28 #include <sys/time.h>
29 #include <unistd.h>
30 #ifdef CONSCRYPT_UNBUNDLED
31 #include <dlfcn.h>
32 #endif  // CONSCRYPT_UNBUNDLED
33 #endif  // !_WIN32
34 
35 namespace conscrypt {
36 namespace netutil {
37 
38 /**
39  * Copied from libnativehelper NetworkUtilites.cpp
40  */
setBlocking(int fd,bool blocking)41 bool setBlocking(int fd, bool blocking) {
42 #ifdef _WIN32
43     unsigned long flag = blocking ? 0UL : 1UL;  // NOLINT(runtime/int)
44     int res = ioctlsocket(fd, FIONBIO, &flag);
45     if (res != NO_ERROR) {
46         JNI_TRACE("ioctlsocket %d failed with error: %d", fd, WSAGetLastError());
47     }
48     return res == NO_ERROR;
49 #else
50     int flags = fcntl(fd, F_GETFL);
51     if (flags == -1) {
52         return false;
53     }
54 
55     if (!blocking) {
56         flags |= O_NONBLOCK;
57     } else {
58         flags &= ~O_NONBLOCK;
59     }
60 
61     return fcntl(fd, F_SETFL, flags) != -1;
62 #endif
63 }
64 
65 }  // namespace netutil
66 }  // namespace conscrypt
67