• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef CONSCRYPT_NETWORKUTIL_H_
18 #define CONSCRYPT_NETWORKUTIL_H_
19 
20 #ifdef _WIN32
21 // Needed for inet_ntop
22 #define _WIN32_WINNT _WIN32_WINNT_WIN8
23 #include <ws2ipdef.h>
24 #include <ws2tcpip.h>
25 #pragma comment(lib, "ws2_32.lib")
26 
27 #include <io.h>
28 #include <winsock2.h>
29 #else // !_WIN32
30 #include <arpa/inet.h>
31 #include <fcntl.h>
32 #include <poll.h>
33 #include <sys/socket.h>
34 #include <sys/syscall.h>
35 #include <sys/time.h>
36 #include <unistd.h>
37 #ifdef CONSCRYPT_UNBUNDLED
38 #include <dlfcn.h>
39 #endif // CONSCRYPT_UNBUNDLED
40 #endif // !_WIN32
41 
42 namespace conscrypt {
43 
44 /**
45  * Network utility methods.
46  */
47 class NetworkUtil {
48 private:
NetworkUtil()49     NetworkUtil() {}
~NetworkUtil()50     ~NetworkUtil() {}
51 
52 public:
53     /**
54      * Copied from libnativehelper NetworkUtilites.cpp
55      */
setBlocking(int fd,bool blocking)56     static inline bool setBlocking(int fd, bool blocking) {
57 #ifdef _WIN32
58         unsigned long flag = blocking ? 0UL : 1UL;
59         int res = ioctlsocket(fd, FIONBIO, &flag);
60         if (res != NO_ERROR) {
61             JNI_TRACE("ioctlsocket %d failed with error: %d", fd, WSAGetLastError());
62         }
63         return res == NO_ERROR;
64 #else
65         int flags = fcntl(fd, F_GETFL);
66         if (flags == -1) {
67             return false;
68         }
69 
70         if (!blocking) {
71             flags |= O_NONBLOCK;
72         } else {
73             flags &= ~O_NONBLOCK;
74         }
75 
76         return fcntl(fd, F_SETFL, flags) != -1;
77 #endif
78     }
79 };
80 
81 }  // namespace conscrypt
82 
83 #endif  // CONSCRYPT_NETWORKUTIL_H_
84