-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPCSBSocket.win.cpp
More file actions
459 lines (406 loc) · 13 KB
/
PCSBSocket.win.cpp
File metadata and controls
459 lines (406 loc) · 13 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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/*
* Copyright (c) 2004, Ben Supnik and Chris Serio.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "PCSBSocket.h"
#include <stdio.h>
#define MAJOR_VERSION_REQUIRED 2
#define MINOR_VERSION_REQUIRED 0
#define BLOCKING 0
#define NON_BLOCKING 1
//FILE * hexdump = fopen("hexdump.txt","w");
//extern FILE * hexdump;
/* Construct a new socket. If the socket is to be a server listening port,
* Pass 0 to dynamically allocate a port or a positive number to pick a
* well-known one. */
PCSBSocket::PCSBSocket(unsigned short inPort, bool inServer)
{
int nResult;
int off = 0;
int on = 1;
socketStatus = status_Ready;
mReceivedRelease = false;
mSentRelease = false;
mIsAServer = false;
sIn.sin_family = AF_INET;
sIn.sin_addr.S_un.S_addr = INADDR_ANY; //Let windows pick a suitable addy
sIn.sin_port = htons(inPort); //Set the local port or if 0 let windows assign one
mWinSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); //start the socket for TCP/IP comms
if(mWinSocket == INVALID_SOCKET)
{
socketStatus = status_Error;
return;
}
if (setsockopt(mWinSocket, IPPROTO_TCP, TCP_NODELAY, (const char *)&on,
sizeof(on))<0)
{
printf("-----------------------Could not set TCP_NODELAY on port %d-------------\n",inPort);
}
if (bind(mWinSocket, (LPSOCKADDR)&sIn, sizeof(sIn)) != 0) //Bind the socket to the local addy
{
socketStatus = status_Error;
return;
}
unsigned long nSetSocketType = NON_BLOCKING;
nResult = ioctlsocket(mWinSocket,FIONBIO,&nSetSocketType); //set to non-blocking
//We're a server so start listening!
if(inServer)
{
mIsAServer = true;
if(listen(mWinSocket, SOMAXCONN))
{
printf("Could not enable listening!");
socketStatus = status_Error;
return;
}
}
}
PCSBSocket::PCSBSocket(SOCKET inWorkerSocket)
{
mWinSocket = inWorkerSocket;
socketStatus = status_Connected;
mReceivedRelease = false;
mSentRelease = false;
mIsAServer = false;
unsigned long nSetSocketType = NON_BLOCKING;
int nResult = ioctlsocket(mWinSocket,FIONBIO,&nSetSocketType); //set to non-blocking
}
/* Start up the networking DLL for the first time. Returns true if
the DLL is ok and sockets can be used. */
/* BAS - note: we ignore the init and shutdown DLL since we can recursively
* open winsock. :-) */
bool PCSBSocket::StartupNetworking(bool inInitDLL)
{
WORD wVersionRequired = MAKEWORD(MAJOR_VERSION_REQUIRED,MINOR_VERSION_REQUIRED);
WSADATA wsaData;
if(WSAStartup(wVersionRequired, &wsaData) != NO_ERROR) //Startup the Winsock2 dll
return false;
if (wsaData.wVersion != wVersionRequired) //Check for version
return false;
return true;
}
/* Tear down the network. Used when the network is all done and ready
to be closed down. */
void PCSBSocket::ShutdownNetworking(bool inCloseDLL)
{
WSACleanup();
}
/* Close the socket. you will be forcefully disconnected if necessary. */
PCSBSocket::~PCSBSocket()
{
closesocket(mWinSocket);
}
PCSBSocket * PCSBSocket::Accept()
{
SOCKET workerSocket = accept(mWinSocket,NULL,NULL);
socketStatus = status_Ready;
if(workerSocket == SOCKET_ERROR)
return NULL; // No one called.
return new PCSBSocket(workerSocket); // Return a new socket object.
}
/* Get the socket's internal status. */
PCSBSocket::Status PCSBSocket::GetStatus(void)
{
TIMEVAL timeout;
timeout.tv_sec = 0; //no timeout!
timeout.tv_usec = 0; //no timeout!
if ((socketStatus == status_Ready) && mIsAServer)
{
fd_set socketSetRead;
FD_ZERO(&socketSetRead);
FD_SET(mWinSocket,&socketSetRead);
int nReturn = select(NULL,&socketSetRead,NULL,NULL,&timeout);
if (nReturn > 0)
{
if(FD_ISSET(mWinSocket,&socketSetRead)) //Able to read on it?
{
socketStatus = status_Connecting;
return socketStatus;
}
else
{
socketStatus = status_Disconnected;
return socketStatus;
}
}
else if(nReturn == 0) //Didn't have enough time to complete request fully (non-blocking)
{
}
else //Must be a socket error :(
{
socketStatus = status_Error;
}
}
if (socketStatus == status_Connecting)
{
fd_set socketSetWrite,socketSetError;
FD_ZERO(&socketSetWrite);
FD_ZERO(&socketSetError);
FD_SET(mWinSocket,&socketSetWrite); //macro to form set
FD_SET(mWinSocket,&socketSetError);
int nReturn = select(NULL,NULL,&socketSetWrite,&socketSetError,&timeout);
// Check to see if our connection completed.
if (nReturn > 0)
{
if((FD_ISSET(mWinSocket,&socketSetWrite)) && !(FD_ISSET(mWinSocket,&socketSetError)))
{ //If the socket is ready to write with no errors
socketStatus = status_Connected;
return socketStatus;
}
else
{
socketStatus = status_Disconnected;
return socketStatus;
}
}
else if(nReturn == 0) //Didn't have enough time to complete request fully (non-blocking)
{
}
else //Must be a socket error :(
{
socketStatus = status_Error;
}
}
return socketStatus;
}
/* Whether an orderly release has been received. Note that it may
not be possible to tell if one has been issued without first reading
buffered data. */
bool PCSBSocket::ReceivedRelease(void)
{
return mReceivedRelease;
}
/* Connect to a server at a port and IP as a client. */
void PCSBSocket::Connect(unsigned long inIP, unsigned short inPort)
{
socketStatus = status_Connecting;
SOCKADDR_IN sOut;
int nResult;
sOut.sin_family = AF_INET;
sOut.sin_port = htons(inPort); //set the remote connection port
sOut.sin_addr.S_un.S_addr = htonl(inIP); //set the remote IP to connect to
nResult = connect(mWinSocket,(LPSOCKADDR)&sOut,sizeof(sOut)); //connect
if(nResult == SOCKET_ERROR)
{
if(WSAGetLastError() != WSAEWOULDBLOCK) //If it's a mere blocking error, check if connection completed by using select()
{
socketStatus = status_Error;
}
}
else
socketStatus = status_Connected; //If it didn't have an error to begin with
}
/* Read as much data from the socket as you want and is possible.
Positive numbers indicate a read, 0 indicates that no data is
available (either due to a lack of data sent or an orderly release).
A negative number indicates an error, either an unknown error or
a disconnect. To further diagnose 0 or -1 responses, use
GetStatus() and ReceivedRelease(). */
long PCSBSocket::ReadData(void* outBuf,long inLength)
{
int nReturn;
nReturn = recv(mWinSocket,(char*)outBuf,inLength,NULL);
if(nReturn == SOCKET_ERROR)
{
nReturn = WSAGetLastError();
if(nReturn == WSAEWOULDBLOCK)
{
//printf("No Data on Socket yet!\n");
return 0; // ** Signal no data
}
else if((nReturn == WSAECONNRESET)||(nReturn == WSAENOTCONN)||(nReturn == WSAETIMEDOUT)||(nReturn == WSAECONNABORTED))
{
socketStatus = status_Disconnected;
return -1;
}
else
{
socketStatus = status_Error; // signal a real error.
return -1; //
}
}
else if(nReturn == 0)
{
mReceivedRelease = true;
if(mSentRelease)
{
socketStatus = status_Disconnected;
return -1;
}
else
return 0;
}
else
{
//printf("%s\n",(char*)outBuf);
return nReturn;
}
}
/* Write as much data to the socket as you want and is possible. Positive
numbers indicate a write, zero indicates that no data was written due to
flow control. -1 indicates that an error occured, either a socket closure
or otherwise. */
long PCSBSocket::WriteData(const void* inBuf,long inLength)
{
int nReturn;
//fprintf(hexdump,"\n");
//DumpHex(hexdump,(char*)inBuf,inLength);
//fflush(hexdump);
nReturn = send(mWinSocket,(char*)inBuf,inLength,NULL);
if(nReturn == SOCKET_ERROR)
{
nReturn = WSAGetLastError();
if(nReturn == WSAEWOULDBLOCK)
{
return 0; // ** Signal no data
}
else if((nReturn == WSAECONNRESET)|| //These errors are okay. They signal the obvious.
(nReturn == WSAENOTCONN)||
(nReturn == WSAETIMEDOUT)||
(nReturn == WSAECONNABORTED)||
(nReturn == WSAESHUTDOWN))
{
socketStatus = status_Disconnected;
return -1;
}
else
{
socketStatus = status_Error; // signal a real error.
return -1;
}
}
else
return nReturn;
}
/* Disconnect the socket now. This will be a disorderly disconnect */
void PCSBSocket::Disconnect(void)
{
shutdown(mWinSocket,SD_SEND|SD_RECEIVE);
socketStatus = status_Disconnected;
}
/* Indicate that you have no more data to send. The socket will be
* closed after the other side finishes sending data. You can still
* call disconnect to force the issue. */
void PCSBSocket::Release(void)
{
if(shutdown(mWinSocket,SD_SEND)==SOCKET_ERROR)
socketStatus = status_Error;
mSentRelease = true;
}
/* Get the local IP address of the machine and port we are bound to.
* Also return the remote side port and IP, or 0 if we're not connected.
* Pass NULL for anything you don't want. */
void PCSBSocket::GetAddresses(ConnectionData* dataStruct)
{
int nReturn;
SOCKADDR_IN tempStruct;
int sizeStruct = sizeof(tempStruct);
/***********************Remote Addresses****************************/
nReturn = getpeername(mWinSocket,(LPSOCKADDR)&tempStruct,&sizeStruct);
dataStruct->remoteIP = ntohl(tempStruct.sin_addr.S_un.S_addr);
dataStruct->remotePort = ntohs(tempStruct.sin_port);
/***********************Local Addresses****************************/
nReturn = getsockname(mWinSocket,(LPSOCKADDR)&tempStruct,&sizeStruct);
dataStruct->localIP = ntohl(tempStruct.sin_addr.S_un.S_addr);
dataStruct->localPort = ntohs(tempStruct.sin_port);
}
/* This function traverses an array of PCSBSockets and returns the
* number of sockets that have I/O that needs to be done. The function
* also sets any array element to 0 that does not need work done to it.
* Therefore, after the function returns normally, the only array elements
* that are non-null are ones that need to have work done. The function
* shall return a -1 if the timeout has elapsed and -2 if there was a socket
* error.*/
int PCSBSocket::WaitForSockets(PCSBSocket** inSockets, int inCount, long inTimeout)
{
int nReturn;
TIMEVAL timeout;
fd_set socketSetWrite, socketSetRead;
//Set the timeout for the select
timeout.tv_sec = inTimeout;
timeout.tv_usec = 0;
FD_ZERO(&socketSetWrite);
FD_ZERO(&socketSetRead);
//The default set array size is 64. If we have more than
//that, we have a problem that we need to deal with by breaking
//the checks up into pieces
//
//TODO: FIX THIS KNOWN PROBLEM!
//For now, just pray that inCount < 64
//Set up the "set" that we want to look through for reads and writes
for(int n = 0; n < inCount; n++)
{
//We can't write to a listener socket and winsock will
//barf if we try.
if(inSockets[n]->mIsAServer == false)
FD_SET(inSockets[n]->mWinSocket, &socketSetWrite);
FD_SET(inSockets[n]->mWinSocket, &socketSetRead);
}
//Check the sockets.
//The massive nasty first argument just determines the maximum size of all possible sets
//and adds 1.
nReturn = select(((socketSetRead.fd_count > socketSetWrite.fd_count)?(socketSetRead.fd_count + 1) : (socketSetWrite.fd_count + 1)),
&socketSetRead,
&socketSetWrite,
NULL,
&timeout);
//The operation timed out
if(nReturn == 0)
return 0;
//If there was no error, let's check to see what needs to be done
if(nReturn != SOCKET_ERROR)
{
for(int n = 0; n < inCount; n++)
{
//See if any reads or writes are ready. If there isn't,
//null out that array element.
if(!(FD_ISSET(inSockets[n]->mWinSocket, &socketSetRead)) &&
!(FD_ISSET(inSockets[n]->mWinSocket, &socketSetWrite)))
inSockets[n] = 0;
}
return nReturn;
}
else
{
return -1; //This is an error!
}
}
/**********************************************************************
* DNS Access
**********************************************************************/
/* Looks up an IP address (dot-number form or DNS form. */
unsigned long PCSBSocket::LookupAddress(const char* inAddress)
{
HOSTENT* host;
struct in_addr *ipAddress;
unsigned long ip;
//try it as an IP first
ip = inet_addr(inAddress);
if (ip != INADDR_NONE)
return ntohl(ip);
host = gethostbyname(inAddress);
if(host == NULL)
return 0;
ipAddress = (struct in_addr *)(host->h_addr);
if (!ipAddress)
return 0;
return ntohl(ipAddress->s_addr);
}