-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathSocket.cpp
More file actions
264 lines (228 loc) · 5.94 KB
/
Socket.cpp
File metadata and controls
264 lines (228 loc) · 5.94 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
#include "pch.h"
#include <cstring>
#include <thread>
#include "Utilities/Socket.h"
#include "Utilities/UPnPPortMapper.h"
using namespace std;
#ifdef _WIN32
#pragma comment(lib,"ws2_32.lib") //Winsock Library
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <Windows.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <unistd.h>
#define INVALID_SOCKET (uintptr_t)-1
#define SOCKET_ERROR -1
#define WSAGetLastError() errno
#define SOCKADDR_IN sockaddr_in
#define SOCKADDR sockaddr
#define TIMEVAL timeval
#define SD_SEND SHUT_WR
#define closesocket close
#define WSAEWOULDBLOCK EWOULDBLOCK
#define ioctlsocket ioctl
#endif
Socket::Socket()
{
#ifdef _WIN32
WSADATA wsaDat;
if(WSAStartup(MAKEWORD(2, 2), &wsaDat) != 0) {
std::cout << "WSAStartup failed." << std::endl;
SetConnectionErrorFlag();
return;
}
_cleanupWSA = true;
#endif
_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(_socket == INVALID_SOCKET) {
std::cout << "Socket creation failed." << std::endl;
SetConnectionErrorFlag();
} else {
SetSocketOptions();
}
}
Socket::Socket(uintptr_t socket)
{
_socket = socket;
if(socket == INVALID_SOCKET) {
SetConnectionErrorFlag();
} else {
SetSocketOptions();
}
}
Socket::~Socket()
{
if(_UPnPPort != -1) {
UPnPPortMapper::RemoveNATPortMapping(_UPnPPort, IPProtocol::TCP);
}
if(_socket != INVALID_SOCKET) {
Close();
}
#ifdef _WIN32
if(_cleanupWSA) {
WSACleanup();
}
#endif
}
void Socket::SetSocketOptions()
{
//Non-blocking mode
u_long iMode = 1;
ioctlsocket(_socket, FIONBIO, &iMode);
//Set send/recv buffers to 256k
int bufferSize = 0x40000;
setsockopt(_socket, SOL_SOCKET, SO_RCVBUF, (char*)&bufferSize, sizeof(int));
setsockopt(_socket, SOL_SOCKET, SO_SNDBUF, (char*)&bufferSize, sizeof(int));
//Disable nagle's algorithm to improve latency
u_long value = 1;
setsockopt(_socket, IPPROTO_TCP, TCP_NODELAY, (char*)&value, sizeof(value));
}
void Socket::SetConnectionErrorFlag()
{
_connectionError = true;
}
void Socket::Close()
{
std::cout << "Socket closed." << std::endl;
shutdown(_socket, SD_SEND);
closesocket(_socket);
SetConnectionErrorFlag();
}
bool Socket::ConnectionError()
{
return _connectionError;
}
void Socket::Bind(uint16_t port)
{
SOCKADDR_IN serverInf;
serverInf.sin_family = AF_INET;
serverInf.sin_addr.s_addr = INADDR_ANY;
serverInf.sin_port = htons(port);
if(UPnPPortMapper::AddNATPortMapping(port, port, IPProtocol::TCP)) {
_UPnPPort = port;
}
if(::bind(_socket, (SOCKADDR*)(&serverInf), sizeof(serverInf)) == SOCKET_ERROR) {
std::cout << "Unable to bind socket." << std::endl;
SetConnectionErrorFlag();
}
}
bool Socket::Connect(const char* hostname, uint16_t port)
{
// Resolve IP address for hostname
bool result = false;
addrinfo hint;
memset((void*)&hint, 0, sizeof(hint));
hint.ai_family = AF_INET;
hint.ai_protocol = IPPROTO_TCP;
hint.ai_socktype = SOCK_STREAM;
addrinfo *addrInfo;
if(getaddrinfo(hostname, std::to_string(port).c_str(), &hint, &addrInfo) != 0) {
std::cout << "Failed to resolve hostname." << std::endl;
SetConnectionErrorFlag();
} else {
//Set socket in non-blocking mode
u_long iMode = 1;
ioctlsocket(_socket, FIONBIO, &iMode);
// Attempt to connect to server
connect(_socket, addrInfo->ai_addr, (int)addrInfo->ai_addrlen);
fd_set writeSockets;
#ifdef _WIN32
writeSockets.fd_count = 1;
writeSockets.fd_array[0] = _socket;
#else
FD_ZERO(&writeSockets);
FD_SET(_socket, &writeSockets);
#endif
//Timeout after 3 seconds
TIMEVAL timeout;
timeout.tv_sec = 3;
timeout.tv_usec = 0;
// check if the socket is ready
int returnVal = select((int)_socket+1, nullptr, &writeSockets, nullptr, &timeout);
if(returnVal > 0) {
result = true;
} else {
//Could not connect
if(returnVal == SOCKET_ERROR) {
//int nError = WSAGetLastError();
//std::cout << "select failed: nError " << std::to_string(nError) << " returnVal" << std::to_string(returnVal) << std::endl;
}
SetConnectionErrorFlag();
}
freeaddrinfo(addrInfo);
}
return result;
}
void Socket::Listen(int backlog)
{
if(listen(_socket, backlog) == SOCKET_ERROR) {
std::cout << "listen failed." << std::endl;
SetConnectionErrorFlag();
}
}
unique_ptr<Socket> Socket::Accept()
{
uintptr_t socket = accept(_socket, nullptr, nullptr);
return unique_ptr<Socket>(new Socket(socket));
}
bool WouldBlock(int nError)
{
return nError == WSAEWOULDBLOCK || nError == EAGAIN;
}
int Socket::Send(char *buf, int len, int flags)
{
int retryCount = 100;
int nError = 0;
int returnVal;
do {
//Loop until everything has been sent (shouldn't loop at all in the vast majority of cases)
returnVal = send(_socket, buf, len, flags);
if(returnVal > 0) {
//Sent partial data, adjust pointer & length
buf += returnVal;
len -= returnVal;
} else if(returnVal == SOCKET_ERROR) {
nError = WSAGetLastError();
if(nError != 0) {
if(!WouldBlock(nError)) {
SetConnectionErrorFlag();
} else {
retryCount--;
if(retryCount == 0) {
//Connection seems dead, close it.
std::cout << "Unable to send data, closing socket." << std::endl;
Close();
return 0;
}
std::this_thread::sleep_for(std::chrono::duration<int, std::milli>(20));
}
}
}
} while(WouldBlock(nError) && len > 0);
return returnVal;
}
int Socket::Recv(char *buf, int len, int flags)
{
int returnVal = recv(_socket, buf, len, flags);
if(returnVal == SOCKET_ERROR) {
int nError = WSAGetLastError();
if(nError && !WouldBlock(nError)) {
std::cout << "recv failed: nError " << std::to_string(nError) << " returnVal" << std::to_string(returnVal) << std::endl;
SetConnectionErrorFlag();
}
} else if(returnVal == 0) {
//Socket closed
std::cout << "Socket closed by peer." << std::endl;
Close();
}
return returnVal;
}