-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket_general.cpp
executable file
·486 lines (382 loc) · 9.43 KB
/
socket_general.cpp
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#include <time.h>
// OS-dependent header files for socket I/O.
#ifdef unix
#include <unistd.h>
#include <sys/socket.h>
#else
#ifdef WIN32
#include <io.h>
#include <winsock2.h>
#endif
#endif
#include <errno.h>
#include "globals.h"
#include "World.h"
#include "socket_general.h"
#include "socket_connection.h"
#include "socket_listener.h"
#include "utility.h"
#include <list>
using namespace std;
tPointerOwner<SocketGeneral> SocketMap;
SocketGeneral::SocketGeneral()
: tManagedObject<SocketGeneral>(SocketMap)
{
FreezeNewOutput = false;
FreezeNewInput = false;
RemoveNow = false;
}
SocketGeneral::~SocketGeneral()
{
}
void SocketGeneral::Disconnect()
{
if (FileDescriptor > 0)
{
#ifdef WIN32
shutdown(FileDescriptor, SD_SEND);
closesocket (FileDescriptor);
#else
close (FileDescriptor);
#endif
}
FileDescriptor = -1;
FreezeNewInput = true;
FreezeNewOutput = true;
}
/////////////////////////////////////////////////////////
SocketManager::SocketManager( )
{
Error = esmeNone;
}
SocketManager::~SocketManager()
{
itorSocketId itor;
for ( itor = Sockets.begin(); itor != Sockets.end(); itor++ )
{
SocketGeneral * socket = SocketMap[*itor];
delete socket; // auto-removes from map
}
}
bool SocketManager::PollSockets(struct timeval timeoutDelay)
{
FD_ZERO(&in_set);
FD_ZERO(&out_set);
FD_ZERO(&exc_set);
short biggestDesc = 0;
Cleanup();
list<idSocket> localList = Sockets;
itorSocketId itor;
// Construct the list of descriptors to check.
for (itor = localList.begin(); itor != localList.end(); itor++)
{
SocketGeneral * socket = SocketMap[*itor];
if ( !socket )
{
// Do not set into the FdSets if it's not
// allocated anymore.
Sockets.remove(*itor); // *itor is ID, socket is pointer
continue;
}
short desc = socket->GetDescriptor();
// A negative desc can happen if the socket was
// disconnected, or closed temporarily, or something...
// also, don't add it if we want to get rid of it now
if (desc == -1 || socket->RemoveNow) continue;
if ( !socket->FreezeNewInput )
FD_SET(desc, &in_set);
if ( socket->WantsToWrite() )
FD_SET(desc, &out_set);
FD_SET(desc, &exc_set);
#ifdef unix
// On windows, we don't need to bother with this.
biggestDesc = MAX(desc, biggestDesc);
#endif
}
if ( select(biggestDesc + 1, &in_set, &out_set, &exc_set, &timeoutDelay) < 0 )
{
switch (errno)
{
case EBADF:
printf("A bad descriptor was given to select.\n");
break;
case EINTR:
printf("A bad descriptor was given to select.\n");
break;
}
Error = esmeCouldntSelect;
return false;
}
Cleanup();
return true;
}
void SocketManager::ForceFlushOutput()
{
FD_ZERO(&in_set);
FD_ZERO(&exc_set);
bool found = false;
short iterations = 0;
do
{
found = false;
struct timeval timeoutDelay;
timeoutDelay.tv_sec = 1;
timeoutDelay.tv_usec = 0;
FD_ZERO(&out_set);
itorSocketId itor;
short biggestDesc = 0;
// Construct the list of descriptors to check.
for (itor = Sockets.begin(); itor != Sockets.end(); itor++)
{
SocketGeneral * socket = SocketMap[*itor];
if ( !socket )
continue;
short desc = socket->GetDescriptor();
if (desc == -1) continue;
if ( socket->IsA(estConnection) && socket->WantsToWrite() )
{
found = true;
FD_SET(desc, &out_set);
}
#ifdef unix
// On windows, we don't need to bother with this.
biggestDesc = MAX(desc, biggestDesc);
#endif
}
if ( select(biggestDesc + 1, NULL, &out_set, NULL, &timeoutDelay) < 0 )
{
Error = esmeCouldntSelect;
return;
}
this->ProcessActiveSockets();
iterations++;
} while (found && iterations < 60); // one minute at most
}
void SocketManager::RemoveSocket(idSocket id, bool removeNow)
{
if ( id == 0 )
return;
// "Further" remove the socket only if it's a valid reference
SocketGeneral * socket = SocketMap[id];
if ( socket )
this->RemoveSocket(socket, removeNow);
else
toDelete.push_back( id );
}
void SocketManager::RemoveSocket(SocketGeneral * socket, bool removeNow)
{
if ( !socket )
return;
//gTheWorld->LogString("Removing socket: " + socket->codeGetFullInfo());
toDelete.push_back( socket->GetId() );
socket->FreezeNewInput = true;
socket->FreezeNewOutput = true;
socket->RemoveNow = removeNow;
}
void SocketManager::Cleanup()
{
if (toDelete.empty())
return;
list<idSocket> localToDelete = toDelete;
itorSocketId itor;
for (itor = localToDelete.begin(); itor != localToDelete.end(); itor++)
{
SocketGeneral * socket = SocketMap[*itor];
if ( !socket )
{
gTheWorld->LogBugString("A null socket was found during cleanup... removing from lists.");
Sockets.remove(*itor);
toDelete.remove(*itor);
continue; // go to next in loop
}
if ( !(socket->WantsToWrite()) || socket->RemoveNow || socket->IsWriteTimingOut() )
{
// delete the socket if it's marked for immediate deletion,
// or if there's nothing left to write
socket->Disconnect();
Sockets.remove(*itor);
toDelete.remove(*itor);
delete socket; // auto-removes from the map
}
}
}
void SocketManager::AddWaiting()
{
if (toAdd.empty())
return;
itorSocketId itor;
for (itor = toAdd.begin(); itor != toAdd.end(); itor++)
{
SocketGeneral * socket = SocketMap[*itor];
if ( !socket )
continue; // abort... but this should never ever happen
Sockets.push_back(*itor);
if ( socket->IsA(estConnection) )
((SocketConnection*) socket)->Initialize(); // initialize the socket
}
toAdd.clear();
}
void SocketManager::ProcessLine(string line, SocketGeneral * socket)
{
if (line.compare("shutdown") == 0)
{
printf("Received shutdown order.\n");
gGameRunning = false;
}
else if (line.compare("quit") == 0)
{
printf("Received quit request from socket!\n");
RemoveSocket(socket);
}
else
{
printf("String: %s. Length: %d.\n",line.c_str(), line.length() );
}
itorSocketId itor;
for (itor = Sockets.begin(); itor != Sockets.end(); itor++)
{
SocketGeneral * socket = SocketMap[*itor];
if (!socket)
continue;
if (socket->IsA(estConnection))
{
line.append("\n");
( (SocketConnection *) socket )->SendText(line);
}
}
}
bool SocketManager::ProcessActiveSockets()
{
// Bail out just in case there are no sockets to check
if (Sockets.empty())
return true;
itorSocketId itor;
// Loop through list of sockets.
for (itor = Sockets.begin(); itor != Sockets.end(); itor++)
{
SocketGeneral * socket = SocketMap[*itor];
if ( !socket )
{
gTheWorld->LogBugString("A null socket was found during socket processing!");
continue;
}
int desc = socket->GetDescriptor();
if ( desc == -1) continue;
if (FD_ISSET(desc, &exc_set))
{
FD_CLR( desc, &in_set );
FD_CLR( desc, &out_set );
socket->InExcSet();
this->RemoveSocket(socket, true);
if (socket->IsA(estListener))
gTheWorld->LogBugString("Exception found and disposed of on listener!\n");
else
gTheWorld->LogBugString("Exception found and disposed of!\n");
continue;
}
if (FD_ISSET(desc, &out_set))
{
if ( !socket->InOutSet() )
{
// Something went wrong.
RemoveSocket(socket, true);
continue;
}
}
if (FD_ISSET(desc, &in_set))
{
if ( !socket->InInSet() )
{
// Something went wrong. Dispose of the socket, and move on.
RemoveSocket(socket, true);
continue;
}
}
if ( socket->IsA(estConnection))
{
if ( ((SocketConnection*) socket )->HasInputBuffer() )
{
((SocketConnection*) socket )->ProcessInputBuffer();
}
}
}
// The listener adds sockets to the waiting list...
// Add them to the main list here.
AddWaiting();
Cleanup();
return true;
}
int SocketManager::CreateListener(int port)
{
SocketListener * listener = new SocketListener(this);
if (!listener->StartListening(port))
{
switch (listener->GetLastError())
{
case esleCreateSocket:
printf("Couldn't create socket.");
break;
case esleSocketOptions:
printf("Couldn't set options.");
break;
case esleCouldntBind:
printf("Couldn't bind.");
break;
case esleCouldntListen:
printf("Couldn't listen.");
break;
default:
break;
}
return -1;
}
Sockets.push_front( listener->GetId() );
return listener->GetDescriptor();
}
bool SocketManager::AddListener(int fileDescriptor)
{
SocketListener * listener = new SocketListener(this);
listener->SetDescriptor(fileDescriptor);
Sockets.push_front( listener->GetId() );
return true;
}
void SocketManager::SendToAll(string line)
{
itorSocketId itor;
for (itor = Sockets.begin(); itor != Sockets.end(); itor++)
{
SocketGeneral * socket = SocketMap[*itor];
if ( socket && socket->IsA(estConnection))
((SocketConnection *) socket)->SendText(line);
}
}
#ifdef WIN32
// Function to initialize Winsock.
bool InitializeWinsock()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
return false;
}
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 ) {
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
WSACleanup( );
return false;
}
/* The WinSock DLL is acceptable. Proceed. */
return true;
}
#endif // win32