forked from embeddedmz/socket-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocket.cpp
More file actions
394 lines (346 loc) · 9.27 KB
/
Socket.cpp
File metadata and controls
394 lines (346 loc) · 9.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/**
* @file Socket.cpp
* @brief implementation of the Socket class
* @author Mohamed Amine Mzoughi <[email protected]>
*/
#include "Socket.h"
#include <cassert>
#include <cstdarg> // va_start, etc.
#include <cstdio> // snprintf
#include <iostream>
#include <vector>
#ifdef _WIN32
// Static members initialization
std::atomic<int> ASocket::s_iSocketCount = ATOMIC_VAR_INIT(0);
WSADATA ASocket::s_wsaData{};
#endif
/**
* @brief constructor of the Socket
*
* @param Logger - a callabck to a logger function void(const std::string&)
*
*/
ASocket::ASocket(const LogFnCallback& oLogger, SettingsFlag eSettings /*= ALL_FLAGS*/)
: m_oLog(oLogger)
, m_eSettingsFlags(eSettings)
{
#ifdef _WIN32
int expected = 0;
if (s_iSocketCount.compare_exchange_strong(expected, 1))
{
InitializeEnvironment();
}
else
{
s_iSocketCount.fetch_add(1, std::memory_order_relaxed);
}
#endif
}
/**
* @brief destructor of the socket object
* It's a pure virtual destructor but an implementation is provided below.
* this to avoid creating a dummy pure virtual method to transform the class
* to an abstract one.
*/
ASocket::~ASocket()
{
#ifdef _WIN32
int value = s_iSocketCount.load(std::memory_order_relaxed);
do
{
if (value == 0)
{
return;
}
if (s_iSocketCount.compare_exchange_weak(value, value - 1))
{
if (value == 1)
{
UnInitializeEnvironment();
}
return;
}
} while(true);
#endif
}
#ifdef _WIN32
bool ASocket::InitializeEnvironment()
{
// In windows, this will init the winsock DLL stuff
// MAKEWORD(2,2) version 2.2 of Winsock
int iWinSockInitResult = WSAStartup(MAKEWORD(2, 2), &s_wsaData);
if (iWinSockInitResult != NO_ERROR)
{
//SocketLog("[ERROR]ASocket, WSAStartup failed[%d:%s]", iWinSockInitResult, strerror(iWinSockInitResult));
return false;
}
if (LOBYTE(s_wsaData.wVersion) != 2 || HIBYTE(s_wsaData.wVersion) != 2)
{
//SocketLog("[ERROR]ASocket, could not find a usable version of winsock.dll[%x]", s_wsaData.wVersion);
return false;
}
return true;
}
void ASocket::UnInitializeEnvironment()
{
/* call WSACleanup when done using the Winsock dll */
WSACleanup();
}
#endif
int ASocket::GetSocketError()
{
#ifdef _WIN32
return WSAGetLastError();
#else
return errno;
#endif
}
char* ASocket::GaiStrerror(int ecode)
{
#ifdef _WIN32
return gai_strerrorA(ecode);
#else
return gai_strerror(ecode);
#endif
}
void ASocket::SocketClose(Socket& sd)
{
if (sd != INVALID_SOCKET)
{
#ifdef _WIN32
closesocket(sd);
#else
close(sd);
#endif
sd = INVALID_SOCKET;
}
}
/**
* @brief returns a formatted string
*
* @param [in] strFormat string with one or many format specifiers
* @param [in] parameters to be placed in the format specifiers of strFormat
*
* @retval string formatted string
*/
std::string ASocket::StringFormat(const char* fmt, ...)
{
if (fmt == NULL)
{
return std::string();
}
va_list args;
va_start(args, fmt);
size_t len = std::vsnprintf(NULL, 0, fmt, args);
va_end(args);
std::vector<char> vec(len + 1);
va_start(args, fmt);
std::vsnprintf(&vec[0], len + 1, fmt, args);
vec[len] = '\0';
va_end(args);
return std::string(vec.data());
}
/**
* @brief waits for a socket's read status change
*
* @param [in] sd socket descriptor to be selected
* @param [in] msec waiting period in milliseconds, a value of 0 implies no timeout
*
* @retval int 0 on timeout, -1 on error and 1 on success.
*/
int ASocket::SelectSocket(Socket sd, size_t msec/* = ACCEPT_WAIT_INF_DELAY*/)
{
if (sd == INVALID_SOCKET)
{
return -1;
}
struct timeval tval{};
struct timeval* tvalptr = nullptr;
if (msec != ACCEPT_WAIT_INF_DELAY)
{
tval.tv_sec = (long)msec / 1000;
tval.tv_usec = (msec % 1000) * 1000;
tvalptr = &tval;
}
fd_set fd_reads{};
FD_ZERO(&fd_reads);
FD_SET(sd, &fd_reads);
#ifdef _WIN32
Socket max_fd = 0;
#else
Socket max_fd = sd + 1;
#endif
// block until socket is readable.
int res = select((int)max_fd, &fd_reads, nullptr, nullptr, tvalptr);
if (res == SOCKET_ERROR)
{
if (SOCKET_ERR_SELECT_RETRIABLE(GetSocketError()))
{
return 0;
}
//SocketLog("[ERROR]ASocket, select failed[%d:%s][%d]", GetSocketError(), strerror(GetSocketError()), max_fd);
return -1;
}
if (res == 0)
{
return 0;
}
#if defined(__unix__) && defined(BSD)
if (!FD_ISSET(sd, &fd_reads))
{
return 0;
}
#endif
assert(FD_ISSET(sd, &fd_reads));
assert(res == 1);
return 1;
}
/**
* @brief waits for a set of sockets read status change
*
* @param [in] pSocketsToSelect pointer to an array of socket descriptors to be selected
* @param [in] count elements count of pSocketsToSelect
* @param [in] msec waiting period in milliseconds, a value of 0 implies no timeout
* @param [out] selectedIndex index of the socket that is ready to be read
*
* @retval int 0 on timeout, -1 on error and 1 on success.
*/
int ASocket::SelectSockets(const Socket* pSocketsToSelect, size_t count, size_t& selectedIndex, size_t msec/* = ACCEPT_WAIT_INF_DELAY*/)
{
if (pSocketsToSelect == nullptr || count == 0)
{
return -1;
}
struct timeval tval{};
struct timeval* tvalptr = nullptr;
if (msec != ACCEPT_WAIT_INF_DELAY)
{
tval.tv_sec = (long)msec / 1000;
tval.tv_usec = (msec % 1000) * 1000;
tvalptr = &tval;
}
fd_set fd_reads{};
FD_ZERO(&fd_reads);
#ifdef _WIN32
Socket max_fd = 0;
#else
Socket max_fd = -1;
#endif
#ifndef _WIN32
for (size_t i = 0; i < count; i++)
{
if (pSocketsToSelect[i] != INVALID_SOCKET)
{
FD_SET(pSocketsToSelect[i], &fd_reads);
if (pSocketsToSelect[i] > max_fd)
{
max_fd = pSocketsToSelect[i];
}
}
}
#endif
#ifndef _WIN32
max_fd += 1;
#endif
// block until one socket is ready to read.
int res = select((int)max_fd, &fd_reads, nullptr, nullptr, tvalptr);
if (res == SOCKET_ERROR)
{
if (SOCKET_ERR_SELECT_RETRIABLE(GetSocketError()))
{
return 0;
}
//SocketLog("[ERROR]ASocket, select failed[%d:%s][%d]", GetSocketError(), strerror(GetSocketError()), max_fd);
return -1;
}
if (res == 0)
{
return 0;
}
// find the first socket which has some activity.
#if defined(__unix__) && defined(BSD)
Socket firstSocket = INVALID_SOCKET;
#endif
for (size_t i = 0; i < count; ++i)
{
if (FD_ISSET(pSocketsToSelect[i], &fd_reads))
{
selectedIndex = i;
#if defined(__unix__) && defined(BSD)
firstSocket = pSocketsToSelect[i];
#endif
break;
}
}
#if defined(__unix__) && defined(BSD)
if (firstSocket == INVALID_SOCKET)
{
return 0;
}
#endif
return 1;
}
bool ASocket::SetRcvTimeout(Socket sd, unsigned int msec_timeout)
{
#ifndef _WIN32
struct timeval t = TimevalFromMsec(msec_timeout);
return SetRcvTimeout(t);
#else
if (setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, (char*)&msec_timeout, sizeof(msec_timeout)) == SOCKET_ERROR)
{
//SocketLog("[ERROR]ASocket, setsockopt SOL_SOCKET SO_RCVTIMEO failed[%d:%s][%d][%u]", GetSocketError(), strerror(GetSocketError()), sd, msec_timeout);
return false;
}
return true;
#endif
}
#ifndef _WIN32
bool ASocket::SetRcvTimeout(Socket sd, const struct timeval& timeout)
{
if (setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)) == SOCKET_ERROR)
{
//SocketLog("[ERROR]ASocket, setsockopt SOL_SOCKET SO_RCVTIMEO failed[%d:%s][%d][%u:%u]", GetSocketError(), strerror(GetSocketError()), sd, timeout.tv_sec, timeout.tv_usec);
return false;
}
return true;
}
#endif
bool ASocket::SetSndTimeout(Socket sd, unsigned int msec_timeout)
{
#ifndef _WIN32
struct timeval t = TimevalFromMsec(msec_timeout);
return SetSndTimeout(t);
#else
if (setsockopt(sd, SOL_SOCKET, SO_SNDTIMEO, (char*)&msec_timeout, sizeof(msec_timeout)) == SOCKET_ERROR)
{
//SocketLog("[ERROR]ASocket, setsockopt SOL_SOCKET SO_SNDTIMEO failed[%d:%s][%d][%u]", GetSocketError(), strerror(GetSocketError()), sd, msec_timeout);
return false;
}
return true;
#endif
}
#ifndef _WIN32
bool ASocket::SetSndTimeout(Socket sd, const struct timeval& timeout)
{
if (setsockopt(sd, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout, sizeof(timeout)) == SOCKET_ERROR)
{
//SocketLog("[ERROR]ASocket, setsockopt SOL_SOCKET SO_SNDTIMEO failed[%d:%s][%d][%u:%u]", GetSocketError(), strerror(GetSocketError()), sd, timeout.tv_sec, timeout.tv_usec);
return false;
}
return true;
}
#endif
/**
* @brief converts a value representing milliseconds into a struct timeval
*
* @param [time_msec] a time value in milliseconds
*
* @retval time_msec converted to struct timeval
*/
struct timeval ASocket::TimevalFromMsec(unsigned int time_msec)
{
struct timeval t{};
t.tv_sec = (long)time_msec / 1000;
t.tv_usec = ((long)time_msec % 1000) * 1000;
return t;
}