socket_wrapper.hpp 8.66 KB
Newer Older
1
2
3
4
/*!
 * Copyright (c) 2016 Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See LICENSE file in the project root for license information.
 */
Guolin Ke's avatar
Guolin Ke committed
5
6
7
8
#ifndef LIGHTGBM_NETWORK_SOCKET_WRAPPER_HPP_
#define LIGHTGBM_NETWORK_SOCKET_WRAPPER_HPP_
#ifdef USE_SOCKET

9
10
#include <LightGBM/utils/log.h>

11
12
13
14
15
#include <string>
#include <cerrno>
#include <cstdlib>
#include <unordered_set>

Guolin Ke's avatar
Guolin Ke committed
16
#if defined(_WIN32)
Guolin Ke's avatar
Guolin Ke committed
17

18
#ifdef _MSC_VER
Guolin Ke's avatar
Guolin Ke committed
19
#define NOMINMAX
20
#endif
Guolin Ke's avatar
Guolin Ke committed
21

Guolin Ke's avatar
Guolin Ke committed
22
23
24
25
26
27
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>

#else

28
#include <arpa/inet.h>
Guolin Ke's avatar
Guolin Ke committed
29
30
31
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
32
#include <netinet/tcp.h>
Guolin Ke's avatar
Guolin Ke committed
33
#include <sys/ioctl.h>
34
#include <sys/socket.h>
Guolin Ke's avatar
Guolin Ke committed
35
#include <sys/types.h>
36
#include <unistd.h>
Guolin Ke's avatar
Guolin Ke committed
37

38
#include <ifaddrs.h>
39

40
#endif  // defined(_WIN32)
Guolin Ke's avatar
Guolin Ke committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

#ifdef _MSC_VER
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "IPHLPAPI.lib")
#endif

namespace LightGBM {

#ifndef _WIN32

typedef int SOCKET;
const int INVALID_SOCKET = -1;
#define SOCKET_ERROR -1

#endif

57
#ifdef _WIN32
58
59
60
#ifndef _UCRT
// Recent MinGW has inet_pton, which then causes compiler error in
// combination with this replacement.
61
62
#ifndef _MSC_VER
// not using visual studio in windows
63
inline int inet_pton(int af, const char *src, void *dst) {
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
  struct sockaddr_storage ss;
  int size = sizeof(ss);
  char src_copy[INET6_ADDRSTRLEN + 1];

  ZeroMemory(&ss, sizeof(ss));
  /* stupid non-const API */
  strncpy(src_copy, src, INET6_ADDRSTRLEN + 1);
  src_copy[INET6_ADDRSTRLEN] = 0;

  if (WSAStringToAddress(src_copy, af, NULL, (struct sockaddr *)&ss, &size) == 0) {
    switch (af) {
    case AF_INET:
      *(struct in_addr *)dst = ((struct sockaddr_in *)&ss)->sin_addr;
      return 1;
    case AF_INET6:
      *(struct in6_addr *)dst = ((struct sockaddr_in6 *)&ss)->sin6_addr;
      return 1;
    }
  }
  return 0;
}
#endif
#endif
87
#endif
88

Guolin Ke's avatar
Guolin Ke committed
89
90
91
92
#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))

namespace SocketConfig {
Guolin Ke's avatar
Guolin Ke committed
93
94
const int kSocketBufferSize = 100 * 1000;
const int kMaxReceiveSize = 100 * 1000;
95
const int kNoDelay = 1;
Guolin Ke's avatar
Guolin Ke committed
96
97
98
}

class TcpSocket {
Nikita Titov's avatar
Nikita Titov committed
99
 public:
Guolin Ke's avatar
Guolin Ke committed
100
101
102
  TcpSocket() {
    sockfd_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sockfd_ == INVALID_SOCKET) {
103
      Log::Fatal("Socket construction error");
Guolin Ke's avatar
Guolin Ke committed
104
105
106
107
108
109
110
111
      return;
    }
    ConfigSocket();
  }

  explicit TcpSocket(SOCKET socket) {
    sockfd_ = socket;
    if (sockfd_ == INVALID_SOCKET) {
112
      Log::Fatal("Passed socket error");
Guolin Ke's avatar
Guolin Ke committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
      return;
    }
    ConfigSocket();
  }

  TcpSocket(const TcpSocket &object) {
    sockfd_ = object.sockfd_;
    ConfigSocket();
  }
  ~TcpSocket() {
  }
  inline void SetTimeout(int timeout) {
    setsockopt(sockfd_, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<char*>(&timeout), sizeof(timeout));
  }
  inline void ConfigSocket() {
    if (sockfd_ == INVALID_SOCKET) {
      return;
    }
131

Guolin Ke's avatar
Guolin Ke committed
132
    if (setsockopt(sockfd_, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<const char*>(&SocketConfig::kSocketBufferSize), sizeof(SocketConfig::kSocketBufferSize)) != 0) {
133
      Log::Warning("Set SO_RCVBUF failed, please increase your net.core.rmem_max to 100k at least");
Guolin Ke's avatar
Guolin Ke committed
134
    }
135

Guolin Ke's avatar
Guolin Ke committed
136
    if (setsockopt(sockfd_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char*>(&SocketConfig::kSocketBufferSize), sizeof(SocketConfig::kSocketBufferSize)) != 0) {
137
      Log::Warning("Set SO_SNDBUF failed, please increase your net.core.wmem_max to 100k at least");
Guolin Ke's avatar
Guolin Ke committed
138
139
    }
    if (setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const char*>(&SocketConfig::kNoDelay), sizeof(SocketConfig::kNoDelay)) != 0) {
140
      Log::Warning("Set TCP_NODELAY failed");
Guolin Ke's avatar
Guolin Ke committed
141
    }
Guolin Ke's avatar
Guolin Ke committed
142
143
144
145
146
147
  }

  inline static void Startup() {
#if defined(_WIN32)
    WSADATA wsa_data;
    if (WSAStartup(MAKEWORD(2, 2), &wsa_data) == -1) {
148
      Log::Fatal("Socket error: WSAStartup error");
Guolin Ke's avatar
Guolin Ke committed
149
150
151
    }
    if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2) {
      WSACleanup();
152
      Log::Fatal("Socket error: Winsock.dll version error");
Guolin Ke's avatar
Guolin Ke committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
    }
#else
#endif
  }
  inline static void Finalize() {
#if defined(_WIN32)
    WSACleanup();
#endif
  }

  inline static int GetLastError() {
#if defined(_WIN32)
    return WSAGetLastError();
#else
    return errno;
#endif
  }



#if defined(_WIN32)
  inline static std::unordered_set<std::string> GetLocalIpList() {
    std::unordered_set<std::string> ip_list;
    char buffer[512];
    // get hostName
    if (gethostname(buffer, sizeof(buffer)) == SOCKET_ERROR) {
179
      Log::Fatal("Error code %d, when getting local host name", WSAGetLastError());
Guolin Ke's avatar
Guolin Ke committed
180
181
182
183
184
185
    }
    // push local ip
    PIP_ADAPTER_INFO pAdapterInfo;
    PIP_ADAPTER_INFO pAdapter = NULL;
    DWORD dwRetVal = 0;
    ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
186
    pAdapterInfo = reinterpret_cast<IP_ADAPTER_INFO *>(MALLOC(sizeof(IP_ADAPTER_INFO)));
Guolin Ke's avatar
Guolin Ke committed
187
    if (pAdapterInfo == NULL) {
188
      Log::Fatal("GetAdaptersinfo error: allocating memory");
Guolin Ke's avatar
Guolin Ke committed
189
190
191
192
193
    }
    // Make an initial call to GetAdaptersInfo to get
    // the necessary size into the ulOutBufLen variable
    if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
      FREE(pAdapterInfo);
194
      pAdapterInfo = reinterpret_cast<IP_ADAPTER_INFO *>(MALLOC(ulOutBufLen));
Guolin Ke's avatar
Guolin Ke committed
195
      if (pAdapterInfo == NULL) {
196
        Log::Fatal("GetAdaptersinfo error: allocating memory");
Guolin Ke's avatar
Guolin Ke committed
197
198
199
200
201
202
203
204
205
      }
    }
    if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) {
      pAdapter = pAdapterInfo;
      while (pAdapter) {
        ip_list.insert(pAdapter->IpAddressList.IpAddress.String);
        pAdapter = pAdapter->Next;
      }
    } else {
206
      Log::Fatal("GetAdaptersinfo error: code %d", dwRetVal);
Guolin Ke's avatar
Guolin Ke committed
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    }
    if (pAdapterInfo)
      FREE(pAdapterInfo);
    return ip_list;
  }
#else
  inline static std::unordered_set<std::string> GetLocalIpList() {
    std::unordered_set<std::string> ip_list;
    struct ifaddrs * ifAddrStruct = NULL;
    struct ifaddrs * ifa = NULL;
    void * tmpAddrPtr = NULL;

    getifaddrs(&ifAddrStruct);

    for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
      if (!ifa->ifa_addr) {
        continue;
      }
      if (ifa->ifa_addr->sa_family == AF_INET) {
Guolin Ke's avatar
Guolin Ke committed
226
        // NOLINTNEXTLINE
Guolin Ke's avatar
Guolin Ke committed
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
        tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
        char addressBuffer[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
        ip_list.insert(std::string(addressBuffer));
      }
    }
    if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct);
    return ip_list;
  }
#endif
  inline static sockaddr_in GetAddress(const char* url, int port) {
    sockaddr_in addr = sockaddr_in();
    std::memset(&addr, 0, sizeof(sockaddr_in));
    inet_pton(AF_INET, url, &addr.sin_addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(static_cast<u_short>(port));
    return addr;
  }

  inline bool Bind(int port) {
    sockaddr_in local_addr = GetAddress("0.0.0.0", port);
    if (bind(sockfd_, reinterpret_cast<const sockaddr*>(&local_addr), sizeof(sockaddr_in)) == 0) {
      return true;
    }
    return false;
  }

  inline bool Connect(const char *url, int port) {
    sockaddr_in  server_addr = GetAddress(url, port);
    if (connect(sockfd_, reinterpret_cast<const sockaddr*>(&server_addr), sizeof(sockaddr_in)) == 0) {
      return true;
    }
    return false;
  }

  inline void Listen(int backlog = 128) {
    listen(sockfd_, backlog);
  }

  inline TcpSocket Accept() {
    SOCKET newfd = accept(sockfd_, NULL, NULL);
    if (newfd == INVALID_SOCKET) {
269
270
271
272
273
274
      int err_code = GetLastError();
#if defined(_WIN32)
      Log::Fatal("Socket accept error (code: %d)", err_code);
#else
      Log::Fatal("Socket accept error, %s (code: %d)", std::strerror(err_code), err_code);
#endif
Guolin Ke's avatar
Guolin Ke committed
275
276
277
278
279
280
281
    }
    return TcpSocket(newfd);
  }

  inline int Send(const char *buf_, int len, int flag = 0) {
    int cur_cnt = send(sockfd_, buf_, len, flag);
    if (cur_cnt == SOCKET_ERROR) {
282
283
284
285
286
287
      int err_code = GetLastError();
#if defined(_WIN32)
      Log::Fatal("Socket send error (code: %d)", err_code);
#else
      Log::Fatal("Socket send error, %s (code: %d)", std::strerror(err_code), err_code);
#endif
Guolin Ke's avatar
Guolin Ke committed
288
289
290
291
292
293
294
    }
    return cur_cnt;
  }

  inline int Recv(char *buf_, int len, int flags = 0) {
    int cur_cnt = recv(sockfd_, buf_ , len , flags);
    if (cur_cnt == SOCKET_ERROR) {
295
296
297
298
299
300
      int err_code = GetLastError();
#if defined(_WIN32)
      Log::Fatal("Socket recv error (code: %d)", err_code);
#else
      Log::Fatal("Socket recv error, %s (code: %d)", std::strerror(err_code), err_code);
#endif
Guolin Ke's avatar
Guolin Ke committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
    }
    return cur_cnt;
  }

  inline bool IsClosed() {
    return sockfd_ == INVALID_SOCKET;
  }

  inline void Close() {
    if (!IsClosed()) {
#if defined(_WIN32)
      closesocket(sockfd_);
#else
      close(sockfd_);
#endif
      sockfd_ = INVALID_SOCKET;
    }
  }

Nikita Titov's avatar
Nikita Titov committed
320
 private:
Guolin Ke's avatar
Guolin Ke committed
321
322
323
324
325
  SOCKET sockfd_;
};

}  // namespace LightGBM
#endif  // USE_SOCKET
Guolin Ke's avatar
Guolin Ke committed
326
#endif   // LightGBM_NETWORK_SOCKET_WRAPPER_HPP_