summaryrefslogtreecommitdiffstats
path: root/src/OSSupport/Socket.cpp
blob: 3248eed88c58cbce4d40770c5d084210012efec8 (plain) (blame)
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

#include "Globals.h"  // NOTE: MSVC stupidness requires this to be the same across all modules

#include "Socket.h"

#ifndef _WIN32
	#include <netdb.h>
	#include <unistd.h>
	#include <arpa/inet.h>		//inet_ntoa()
#else
	#define socklen_t int
#endif





cSocket::cSocket(xSocket a_Socket)
	: m_Socket(a_Socket)
{
}





cSocket::~cSocket()
{
	// Do NOT close the socket; this class is an API wrapper, not a RAII!
}





cSocket::operator cSocket::xSocket() const
{
	return m_Socket;
}





cSocket::xSocket cSocket::GetSocket() const
{
	return m_Socket;
}





bool cSocket::IsValidSocket(cSocket::xSocket a_Socket)
{
	#ifdef _WIN32
	return (a_Socket != INVALID_SOCKET);
	#else  // _WIN32
	return (a_Socket >= 0);
	#endif  // else _WIN32
}





void cSocket::CloseSocket()
{
	#ifdef _WIN32
	
	closesocket(m_Socket);
	
	#else  // _WIN32
	
	if (close(m_Socket) != 0)
	{
		LOGWARN("Error closing socket %d (%s): %s", m_Socket, m_IPString.c_str(), GetLastErrorString().c_str());
	}
	
	#endif  // else _WIN32

	// Invalidate the socket so that this object can be re-used for another connection
	m_Socket = INVALID_SOCKET;
}





void cSocket::ShutdownReadWrite(void)
{
	#ifdef _WIN32
		int res = shutdown(m_Socket, SD_BOTH);
	#else
		int res = shutdown(m_Socket, SHUT_RDWR);
	#endif
	if (res != 0)
	{
		LOGWARN("%s: Error shutting down socket %d (%s): %d (%s)",
			__FUNCTION__, m_Socket, m_IPString.c_str(), this->GetLastError(), GetLastErrorString().c_str()
		);
	}
}




int cSocket::GetLastError()
{
#ifdef _WIN32
	return WSAGetLastError();
#else
	return errno;
#endif
}





bool cSocket::SetReuseAddress(void)
{
	#if defined(_WIN32) || defined(ANDROID_NDK)
		char yes = 1;
	#else
		int yes = 1;
	#endif
	return (setsockopt(m_Socket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == 0);
}





int cSocket::WSAStartup(void)
{
#ifdef _WIN32
	WSADATA wsaData;
	memset(&wsaData, 0, sizeof(wsaData));
	return ::WSAStartup(MAKEWORD(2, 2),&wsaData);
#else
	return 0;
#endif
}





cSocket cSocket::CreateSocket(eFamily a_Family)
{
	return socket((int)a_Family, SOCK_STREAM, 0);
}





bool cSocket::BindToAnyIPv4(unsigned short a_Port)
{
	sockaddr_in local;
	memset(&local, 0, sizeof(local));

	local.sin_family = AF_INET;
	local.sin_port = htons((u_short)a_Port);

	return (bind(m_Socket, (sockaddr *)&local, sizeof(local)) == 0);
}





bool cSocket::BindToAnyIPv6(unsigned short a_Port)
{
	sockaddr_in6 local;
	memset(&local, 0, sizeof(local));

	local.sin6_family = AF_INET6;
	local.sin6_port = htons((u_short)a_Port);

	return (bind(m_Socket, (sockaddr *)&local, sizeof(local)) == 0);
}





bool cSocket::BindToLocalhostIPv4(unsigned short a_Port)
{
	sockaddr_in local;
	memset(&local, 0, sizeof(local));

	local.sin_family = AF_INET;;
	local.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
	local.sin_port = htons((u_short)a_Port);

	return (bind(m_Socket, (sockaddr*)&local, sizeof(local)) == 0);
}





bool cSocket::Listen(int a_Backlog)
{
	return (listen(m_Socket, a_Backlog) == 0);
}





cSocket cSocket::AcceptIPv4(void)
{
	sockaddr_in from;
	socklen_t fromlen = sizeof(from);

	cSocket SClient = accept(m_Socket, (sockaddr *)&from, &fromlen);

	if (SClient.IsValid() && (from.sin_addr.s_addr != 0))  // Get IP in string form
	{
		SClient.m_IPString = inet_ntoa(from.sin_addr);
	}
	return SClient;
}





cSocket cSocket::AcceptIPv6(void)
{
	sockaddr_in6 from;
	socklen_t fromlen = sizeof(from);

	cSocket SClient = accept(m_Socket, (sockaddr *)&from, &fromlen);

	// Get IP in string form:
	if (SClient.IsValid())
	{
		#if defined(_WIN32)
			// Windows XP doesn't have inet_ntop, so we need to improvise. And MSVC has different headers than GCC
			#ifdef _MSC_VER
				// MSVC version
				Printf(SClient.m_IPString, "%x:%x:%x:%x:%x:%x:%x:%x", 
					from.sin6_addr.u.Word[0],
					from.sin6_addr.u.Word[1],
					from.sin6_addr.u.Word[2],
					from.sin6_addr.u.Word[3],
					from.sin6_addr.u.Word[4],
					from.sin6_addr.u.Word[5],
					from.sin6_addr.u.Word[6],
					from.sin6_addr.u.Word[7]
				);
			#else  // _MSC_VER
				// MinGW
				Printf(SClient.m_IPString, "%x:%x:%x:%x:%x:%x:%x:%x", 
					from.sin6_addr.s6_addr16[0],
					from.sin6_addr.s6_addr16[1],
					from.sin6_addr.s6_addr16[2],
					from.sin6_addr.s6_addr16[3],
					from.sin6_addr.s6_addr16[4],
					from.sin6_addr.s6_addr16[5],
					from.sin6_addr.s6_addr16[6],
					from.sin6_addr.s6_addr16[7]
				);
			#endif  // else _MSC_VER
		#else
			char buffer[INET6_ADDRSTRLEN];
			inet_ntop(AF_INET6, &(from.sin6_addr), buffer, sizeof(buffer));
			SClient.m_IPString.assign(buffer);
		#endif  // _WIN32
	}
	return SClient;
}





bool cSocket::ConnectToLocalhostIPv4(unsigned short a_Port)
{
	sockaddr_in server;
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
	server.sin_port = htons(a_Port);
	return (connect(m_Socket, (sockaddr *)&server, sizeof(server)) == 0);
}





bool cSocket::ConnectIPv4(const AString & a_HostNameOrAddr, unsigned short a_Port)
{
	// First try IP Address string to hostent conversion, because it's faster
	unsigned long addr = inet_addr(a_HostNameOrAddr.c_str());
	if (addr == INADDR_NONE)
	{
		// It is not an IP Address string, but rather a regular hostname, resolve:
		hostent * hp = gethostbyname(a_HostNameOrAddr.c_str());
		if (hp == NULL)
		{
			LOGWARNING("%s: Could not resolve hostname \"%s\"", __FUNCTION__, a_HostNameOrAddr.c_str());
			CloseSocket();
			return false;
		}
		addr = *((unsigned long*)hp->h_addr);
	}

	sockaddr_in server;
	server.sin_addr.s_addr = addr;
	server.sin_family = AF_INET;
	server.sin_port = htons((unsigned short)a_Port);
	return (connect(m_Socket, (sockaddr *)&server, sizeof(server)) == 0);
}





int cSocket::Receive(char * a_Buffer, unsigned int a_Length, unsigned int a_Flags)
{
	return recv(m_Socket, a_Buffer, a_Length, a_Flags);
}





int cSocket::Send(const char * a_Buffer, unsigned int a_Length)
{
	return send(m_Socket, a_Buffer, a_Length, MSG_NOSIGNAL);
}





unsigned short cSocket::GetPort(void) const
{
	ASSERT(IsValid());
	
	sockaddr_in Addr;
	socklen_t AddrSize = sizeof(Addr);
	if (getsockname(m_Socket, (sockaddr *)&Addr, &AddrSize) != 0)
	{
		return 0;
	}
	return ntohs(Addr.sin_port);
}





void cSocket::SetNonBlocking(void)
{
	#ifdef _WIN32
		u_long NonBlocking = 1;
		int res = ioctlsocket(m_Socket, FIONBIO, &NonBlocking);
		if (res != 0)
		{
			LOGERROR("Cannot set socket to non-blocking. This would make the server deadlock later on, aborting.\nErr: %d, %d, %s",
				res, GetLastError(), GetLastErrorString().c_str()
			);
			abort();
		}
	#else
		int NonBlocking = 1;
		int res = ioctl(m_Socket, FIONBIO, (char *)&NonBlocking);
		if (res != 0)
		{
			LOGERROR("Cannot set socket to non-blocking. This would make the server deadlock later on, aborting.\nErr: %d, %d, %s",
				res, GetLastError(), GetLastErrorString().c_str()
			);
			abort();
		}
	#endif
}